Search code examples
javauser-interfaceswingjcombobox

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?


Solution

  • 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 )
    }