我创建了一个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中的每个comboBox中获取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();
并且程序没有编译。
答案 0 :(得分:0)
将ActionListner
添加到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);
//////////////// 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
}
}
答案 1 :(得分:0)
我终于明白了。我不得不将ArrayList创建为静态实例变量
private static ArrayList<JComboBox> comboList;
然后在构造函数
中实例化它comboList = new ArrayList<>();
新的courseUnit()方法现在看起来像这个
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);
comboUnits.setToolTipText("Select course unit");
y += 30;
comboUnits.setVisible(true);
add(comboUnits);
//I added ActionListener to each comboBox in the ArrayList,
//thanks to Junaid for this
comboUnits.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
ArrayList<String> courseGrade = new ArrayList<>();
JComboBox comboBox = (JComboBox) evt.getSource();
courseGrade.add((String) comboBox.getSelectedItem());
}
});
comboList.add(comboUnits);
}//end of loop
} //end of method