Netbeans - input elements in jComboBox

I created a GUI from netbeans, in which I also placed a combo box.

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

But I need my own items. Netbeans does not allow editing the generated code, since I can edit comnbobox for me.

Note. I know one method when editing the "model" property of this jComboBox, but I do not want to do it this way because I want this jComboBox to have different elements (which are in the array), so I want to go through this array in this jComboBox looks in the following way:

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)); 
+6
java jcombobox netbeans
source share
5 answers

There are two approaches that I know of:

  • A simple approach. After calling initComponents() in the constructor, add code to build the model and call jComboBox2.setModel(myModel) to set it. Thus, the constructor will look something like this:

     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)); } 
  • An integrated approach - adding a readable property that contains the desired model. For example:

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

    Then, in the jComboBox2 properties window, click the button to edit the model.

    In the editor panel, change the drop-down menu from Combo Box Model Editor to Value from existing component .

    Select Property . Select the comboBoxModel property. Click OK

I tried the second way once. Never used it again. Too much work, no real gain. In addition, it displays an empty combo box in the designer, which simply simplifies the layout.

I use the first approach and also use the NetBean model editor to provide some representative values ​​for the model. This gives me reasonable size behavior in the designer due to one extra line in initComments() .

+7
source share

you can enter your code using the "custom code" function in the GUI editor for the "model" combobox

+2
source share

To complete the blurec answer (I can’t comment yet), in the GUI editor, select comboxbox, go to properties, then model, and then click three dots. Then select Custome Code and add your code, for example:

 new DefaultComboBoxModel<>(functionThatReturnsAnStringArray()) 
0
source share

Using Netbeans NEON and other versions of netbeans

1. Go to the drop-down list properties

enter image description here

2. Then go to the model

enter image description here

0
source share
 public NewJFrame() { initComponents(); reformatComboBox(); } private void reformatComboBox() { JComboBoxName.removeAllItems(); JComboBoxName.addItem("item1"); JComboBoxName.addItem("item2"); } 
0
source share

All Articles