how to add elements in jcombobox dynamically?

4.2k Views Asked by At
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

I want to know ,how to add elements in the comboBox at the run-time?

2

There are 2 best solutions below

3
On

"I want to know ,how to add elements in the comboBox at the run-time?"

See DefaultComboBoxModel#addElement

  • public void addElement(E anObject)

Description copied from interface: MutableComboBoxModel
Adds an item at the end of the model. The implementation of this method should notify all registered ListDataListeners that the item has been added.

In your case, since you have no reference to the model, you need to do this

DefaultComboBoxModel model = (DefaultComboBoxModel)jComboBox2.getModel();
model.addElement(...)

And see How to Use ComboBoxes


Also learn to read the Documentation. Just go Here and you could've searched DefaultComboBoxModel or any other class you are unfamiliar with.

0
On

I guess that Answer would help for you.

i copied this from that answer.

If your combobox has a MutableComboBoxModel, you can do the following

MutableComboBoxModel model = (MutableComboBoxModel)combo.getModel();
model.addElement( elementToAdd );

This is equivalent to calling JComboBox#addItem (see below for the implementation):

public void addItem(Object anObject) {
    checkMutableComboBoxModel();
    ((MutableComboBoxModel)dataModel).addElement(anObject);
}

But I think it is a best practice to modify the model directly if you want to make changes on the model side, and not go through the view (except to provide the user the ability to edit in the view)