Dynamically adding items to a JComboBox

raj picture raj · Sep 12, 2011 · Viewed 92.2k times · Source
Vector comboBoxItems = new Vector();
DefaultComboBoxModel model;
// ComboBox Items have gotten from Data Base initially.
model = new DefaultComboBoxModel(ComboBoxItems);
JComboBox box = new JComboBox(model);

I added this combo box to a panel. If I add some items in the database directly, I want those newly added items shown in the combo box.

I can see the values in comboBoxItems when I debug, but those values do not appear in my combo box.

How can I get those newly added values into the combo box without closing the panel?

Answer

Harry Joy picture Harry Joy · Sep 12, 2011

How about using ComboBoxModel? Something like this....

    JFrame frame = new JFrame("Combo Box Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 200);
    frame.setLayout(new FlowLayout());

    Vector comboBoxItems=new Vector();
    comboBoxItems.add("A");
    comboBoxItems.add("B");
    comboBoxItems.add("C");
    comboBoxItems.add("D");
    comboBoxItems.add("E");
    final DefaultComboBoxModel model = new DefaultComboBoxModel(comboBoxItems);
    JComboBox comboBox = new JComboBox(model);
    frame.add(comboBox);

    JButton button = new JButton("Add new element in combo box");
    frame.add(button);
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            model.addElement("F");
        }
    });

    frame.setVisible(true);