如何使用Array或ArrayList中的值加载JComboBox?

时间:2022-09-15 16:30:15

I need to put the following array into a JComboBox and then store the selected value when the "Submit" button is clicked.

我需要将以下数组放入JComboBox,然后在单击“提交”按钮时存储所选值。

    listOfDepartments = new String[5];
    listOfDepartments[0] = "Mens Clothing";
    listOfDepartments[1] = "Womens Clothing";
    listOfDepartments[2] = "Childrens Clothing";
    listOfDepartments[3] = "Electronics";
    listOfDepartments[4] = "Toys";

    //Department: ComboBox that loads from array

    // Store values
    JButton buttonSubmit = new JButton();
    buttonSubmit.setText("Submit");
    container.add(buttonSubmit);

     buttonSubmit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
        //store value from combobox in a variable
        }
    });

1 个解决方案

#1


7  

First, create a model...

首先,创建一个模型......

DefaultComboBoxModel model = new DefaultComboBoxModel(listOfDepartments);
comboBox.setModel(model);

Second, get the selected value when the actionPerformed event is raised...

其次,在引发actionPerformed事件时获取所选值...

String value = (String)comboBox.getSelectedItem();

Take a look at How to Use Combo Boxes for more details.

请查看如何使用组合框了解更多详细信息。

#1


7  

First, create a model...

首先,创建一个模型......

DefaultComboBoxModel model = new DefaultComboBoxModel(listOfDepartments);
comboBox.setModel(model);

Second, get the selected value when the actionPerformed event is raised...

其次,在引发actionPerformed事件时获取所选值...

String value = (String)comboBox.getSelectedItem();

Take a look at How to Use Combo Boxes for more details.

请查看如何使用组合框了解更多详细信息。