Java Swing How to - Add Item to JComboBox








Question

We would like to know how to add Item to JComboBox.

Answer

import java.awt.BorderLayout;
import java.awt.GridLayout;
//  w  ww  . j  a v  a2 s.c o  m
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class Main {
  public static void main(String args[]) {
    JPanel p = new JPanel();

    p.setLayout(new GridLayout(2, 1));
    JList<String> lista = new JList<>(new String[] {"1", "2", "3", "4"});
    p.add(new JScrollPane(lista));
    JComboBox<String> combo = new JComboBox<>();
    for (int i = 0; i < 100; i++) {
      combo.addItem(Integer.toString(i));
      p.add(combo);
    }
    
    JFrame f = new JFrame();
    f.getContentPane().add(p, BorderLayout.CENTER);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(200, 200);
    f.setVisible(true);
  }
}