Yatendra Goel Yatendra Goel - 5 months ago 14
Java Question

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


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" }));


Can I set another ComboBoxModel to the above jComboBox?


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


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.


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 )