gpt4 book ai didi

java - JComboBox 的 ArrayList

转载 作者:太空宇宙 更新时间:2023-11-04 14:21:46 24 4
gpt4 key购买 nike

我创建了一个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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com