[英]ArrayList of JComboBoxes
I created an ArrayList of JComboBox 我创建了一个JComboBox的ArrayList
private static ArrayList<JComboBox> comboList = new ArrayList<>();
and then added each instance of JComboBox
to the ArrayList
然后将
JComboBox
每个实例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
}
}
My question is, how do i get the selectedItem from each comboBox in the ArrayList because i tried this 我的问题是,我如何从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();
and the program didn't compile. 并且程序没有编译。
You can should attach ActionListner
while you are adding the JComboBox
to the ArrayList
将
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
}
}
I finally got it. 我终于明白了。 I had to create the ArrayList as a static instance variable
我必须将ArrayList创建为静态实例变量
private static ArrayList<JComboBox> comboList;
and then instantiated it in the constructor 然后在构造函数中实例化它
comboList = new ArrayList<>();
The new courseUnit() method now looks like this 新的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.