Netbeans - Entering items in a jComboBox

Yatendra Goel picture Yatendra Goel · Oct 9, 2009 · Viewed 60.4k times · Source

I have generated a GUI from netbeans in which I have placed a combobox too.

By default, the items in combobox are item1, item2, item3, item4.

But I want my own items. Netbeans doesn't allow editing generated code so how can i edit the comnbobox according to me.

Note: I know one method by editing the "model" property of that jComboBox but I don't want to do it like that because I want various items (which are in an array) in that jComboBox so I want to pass that array in that jComboBox like as follows:

jComboBox2 = new javax.swing.JComboBox();

String [] date = new String[31];
for(int i = 0; i < 31; i++) {
    date[i] = i + 1;
}

jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(date));

Answer

Devon_C_Miller picture Devon_C_Miller · Oct 28, 2009

There are 2 approaches I am aware of:

  1. Simple approach - After the call to initComponents() in the constructor add you code to build your model and call jComboBox2.setModel(myModel) to set it. So the constructor would look something like:

    public SomeClass() {
        initComponents();
        String [] date = new String[31];
        for(int i = 0; i < 31; i++) {
            date[i] = i + 1;
        }
        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(date));
    }
    
  2. Complex approach - add a readable property that holds the desired model. For example:

    private ComboBoxModel getComboBoxModel()
    {
        String[] items = {"Item A", "Item B", "Item C"};
        return new DefaultComboBoxModel(items);
    }
    

    Then, in the jComboBox2 property sheet, click the button to edit the model.

    In the editor panel change the dropdown from Combo Box Model Editor to Value from existing component.

    Select Property. Choose the comboBoxModel property. Click OK

I tried the second way once. Never really used it again. Too much work, no real much gain. Plus it displays an empty combo box in the designer which just makes layout harder.

I use the first approach, plus use NetBean's model editor to supply some representative values for the model. That gives me the sensible size behavior in the designer at the cost of one unnecessary line in initComments().