How to load already created JComboBox with data in Java?

I have a Swings GUI that contains a JComboBox, and I want to load data from a database into it.

I got the data from the database in a String Array. Now how can I populate this String array in a JComboBox

EDITED =================================================== =====================

In fact, a JComboBox is already created when the user interface GUI is displayed. Therefore, I cannot pass an array as a parameter to the constructor.

How can I populate an already created JComboBox?

Below is the code that is generated by the sky.

jComboBox15 = new javax.swing.JComboBox();

jComboBox15.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "12" }));

jComboBox15.setName("jComboBox15");

Is it possible to install another ComboBoxModel for the above jComboBox?

+3
5

: Combo Boxes ( Java)

:

String[] dbData = dateFromDb();
JComboBox dbCombo = new JComboBox(dbData);

,

  • Uneditable Combo Box
  • API- Combo Box
  • Combo Boxes

.

Yeap, , , :

DefaultComboBoxModel dcm = new DefaultComboBoxModel();
combo.setModel( dcm );
....
for( String newRow : dataFetched ) {
    dcm.addElement( newRow )
}
+2

Ah, ... :

comboBox.removeAllItems();

for(String str : strArray) {
   comboBox.addItem(str);
}

, EDT!

+3

, , NetBeans, - , .

, DefaultComboBoxModel, comboBox.setModel(defaultComboBox);

, , , : " ", comboBox ( actionPerformed).

public class TestJComboBox extends JFrame {
    private JComboBox comboBox = new JComboBox();

    public TestJComboBox() {

        JButton changeComboBoxData = new JButton("Change data");
        changeComboBoxData.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                DefaultComboBoxModel cbm = new DefaultComboBoxModel(
                        new String[] { "hola", "adios" });
                comboBox.setModel(cbm);
            }
        });

        super.setLayout(new BorderLayout(10, 10));
        super.setSize(100, 100);
        super.add(changeComboBoxData, BorderLayout.NORTH);
        super.add(comboBox, BorderLayout.SOUTH);
    }

    public static void main(String[] args) {
        new TestJComboBox().setVisible(true);
    }
}
+3
new JComboBox(stringArray);

- , , javadoc. .

: :

for (String string : stringArray) {
   comboBox.addItem(string);
}

( - )

+2
JComboBox jComboOperator = new JComboBox();

arrOperatorName = new String []{"Visa", "MasterCard", "American Express"};
jComboOperator.setModel(new DefaultComboBoxModel(arrOperatorName));
0

Source: https://habr.com/ru/post/1729107/


All Articles