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