Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load already instantiated JComboBox with data in Java?

I have a Swings GUI which contains a JComboBox and I want to load data into it from the database.

I have retrieved the data from the database in a String Array. Now how can I populate this String array into the JComboBox

EDITED====================================================================

In actual, the JComboBox is already instantiated when the java GUI is shown to the user. So I can't pass the Array as a paramter to the constructor.

How can I populate the already instantiated JComboBox?

The following is the code that is Nebeans generated code.

jComboBox15 = new javax.swing.JComboBox();

jComboBox15.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "12" }));

jComboBox15.setName("jComboBox15");

Can I set another ComboBoxModel to the above jComboBox?

like image 639
Yatendra Avatar asked Dec 10 '22 17:12

Yatendra


2 Answers

Ah, the combo box is already instantiated.... In that case just clear the contents and add the new array item by item:

comboBox.removeAllItems();

for(String str : strArray) {
   comboBox.addItem(str);
}

Make sure this is done from the EDT!

like image 154
Jason Nichols Avatar answered Dec 12 '22 07:12

Jason Nichols


Here's an excellent article about it: How to use Combo Boxes ( The Java Tutorial )

Basically:

String[] dbData = dateFromDb();
JComboBox dbCombo = new JComboBox(dbData);

You'll need to know other things like

  • Using an Uneditable Combo Box
  • Handling Events on a Combo Box
  • Using an Editable Combo Box
  • Providing a Custom Renderer
  • The Combo Box API
  • Examples that Use Combo Boxes

That article contains information about it.

EDIT

Yeap, you can either do what you show in your edited post, or keep a reference to the combo model:

DefaultComboBoxModel dcm = new DefaultComboBoxModel();
combo.setModel( dcm );
....
for( String newRow : dataFetched ) {
    dcm.addElement( newRow )
}
like image 40
OscarRyz Avatar answered Dec 12 '22 07:12

OscarRyz