java - JComboBox 的 ArrayList

标签 java swing jcombobox

我创建了一个JComboBox的ArrayList

private static ArrayList<JComboBox> comboList = new ArrayList<>();

然后将 JComboBox 的每个实例添加到 ArrayList

private void courseUnit() {
        String[] units = {"6", "5", "4", "3", "2", "1"};
        int x = 520, y = 30;
        for (int i = 0; i < 10; i++) {
            comboUnits = new JComboBox<>(units);
            comboUnits.setBounds(x, y, 100, 25);
            y += 30;
            comboUnits.setToolTipText("Select course unit");
            comboUnits.setVisible(true);
            comboUnits.addActionListener(new PaneAction());
            add(comboUnits);
            comboList.add(comboUnits); //comboUnits added to ArrayList
        }
    }

我的问题是,如何从 ArrayList 中的每个组合框中获取 selectedItem 因为我尝试了这个

//this is supposed to get the selected item of the first ComboBox and assign to courseGrade[0]
    public void actionPerformed(ActionEvent evt) {
            String[] courseGrade = new String[10];
            courseGrade[0] = (String)comboList.get(0).getSelectedItem();

程序没有编译。

最佳答案

您可以在将 JComboBox 添加到 ArrayList 时附加 ActionListner

    private void courseUnit() {
            String[] units = {"6", "5", "4", "3", "2", "1"};
            int x = 520, y = 30;
            for (int i = 0; i < 10; i++) {
                comboUnits = new JComboBox<>(units);
                comboUnits.setBounds(x, y, 100, 25);
                y += 30;
                comboUnits.setToolTipText("Select course unit");
                comboUnits.setVisible(true);
                //comboUnits.addActionListener(new PaneAction());
                add(comboUnits);

//////////////// Here are the changes

                comboUnits.addActionListener (new ActionListener () {
                   public void actionPerformed(ActionEvent e) {
                      String selectedItem = (String)e.getSelectedItem();
                   }
                });
                comboList.add(comboUnits); //comboUnits added to ArrayList
            }
        }

关于java - JComboBox 的 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27104121/

相关文章:

java - Android MediaPlayer 已定稿但未发布

java - Vaadin - 突出显示表格选定的单元格/行

java - 如果不推荐使用 Swing,还有什么替代方案?

java - JFrame 的实际大小

java - 以编程方式创建带有文本的 SplashScreen 的最佳示例

java - 为什么 JComboBox 忽略 PrototypeDisplayValue

java - jcombobox 中的键/值对

java - 更新组合框模型 - 项目监听器不再触发

java - 是否可以持久化对象的类?

java - 更改 UIDefaults 中的 JFrame 边框