I am fetching the data values from the database successfully. I have also stored them into a String[]
array. I need to load the String array as the items of the JComboBox
in response to key actionperformed. How can I reload the items of the JComboBox
whenever a key is pressed as the fetched values depend on the key pressed. Rather simply, I need to dynamically refresh the JComboBox
items.
Asked
Active
Viewed 5.7k times
26

Jordi Castilla
- 26,609
- 8
- 70
- 109

Suman.hassan95
- 3,895
- 8
- 26
- 24
3 Answers
41
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>( yourStringArray );
comboBox.setModel( model );
-
Thanks for your Answer but can you please post a code to illustrarte this. it will be very helpfull. I am not sure of what to write in the DefaultComboBoxModel class. – Suman.hassan95 Jan 06 '11 at 22:06
-
That is the code. You don't write anything in the DefaultComboBoxModel class. You just create the model using your array of strings and then add the model to the combo box. – camickr Jan 06 '11 at 22:12
7
This is the demo for illustrating default combo box model
public class ComboPanel extends JPanel {
JComboBox jcbo;
// this is constructor
public ComboPanel(ArrayList<String> items) {
jcbo = new JComboBox();
// getting exiting combo box model
DefaultComboBoxModel model = (DefaultComboBoxModel) jcbo.getModel();
// removing old data
model.removeAllElements();
for (String item : items) {
model.addElement(item);
}
// setting model with new data
jcbo.setModel(model);
// adding combobox to panel
this.add(jcbo);
}
}
I hope this will help little :)

Mizuki
- 2,153
- 1
- 17
- 29
7
You have a couple of options. You can use removeAllItems()
(or one of the other remove methods) and addItem(Object anObject)
to manipulate the selectable objects. Or you could implement a ComboBoxModel
and allow it to serve up data from your array.

unholysampler
- 17,141
- 7
- 47
- 64