Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Netbeans - Entering items in a jComboBox

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));
like image 785
Yatendra Avatar asked Oct 09 '09 06:10

Yatendra


3 Answers

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().

like image 80
Devon_C_Miller Avatar answered Oct 31 '22 14:10

Devon_C_Miller


Using Netbeans NEON and other netbeans version

1. Go to the properties of the combobox

enter image description here

2. Then go to model

enter image description here

like image 45
Omari Victor Omosa Avatar answered Oct 31 '22 14:10

Omari Victor Omosa


you can inject your code by using "custom code" feature in the GUI editor for the "model" of combobox

like image 25
blurec Avatar answered Oct 31 '22 14:10

blurec