JComboBox[] ChooseType = new JComboBox[a];
JRadioButton[] Primary = new JRadioButton[a];
ButtonGroup group = new ButtonGroup();
for (int b = 0; b < a; b++) {
ChooseType[b] = new JComboBox(Types);
Primary[b] = new JRadioButton();
group.add(Primary[b]);
Primary[b].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ChooseType[b].setSelectedIndex(8);//Error here
}
});
}
I already tried this:
final JComboBox[] ChooseType = new JComboBox[a];
I tried also to create a inner class and a method, so I dont have to deal directly with the JComboBox inside the actionPerformed. Can someone tell me how to fix it?
The problem is with the b
variable. You can use a temporary variable:
for (int b = 0; b < a; b++) {
int b0 = b;
chooseType[b] = new JComboBox(Types);
//...
chooseType[b0].setSelectedIndex(8);//Error here
ps: I've changed the capitalisation of the variable to match Java's conventions.
To simply put it in code:
JComboBox[] ChooseType = new JComboBox[a];
JRadioButton[] Primary = new JRadioButton[a];
ButtonGroup group = new ButtonGroup();
for (int b = 0; b < a; b++) {
//This is the item that's not final
ChooseType[b] = new JComboBox(Types);
Primary[b] = new JRadioButton();
group.add(Primary[b]);
final JComboBox forListener = ChooseType[b];
Primary[b].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
forListener.setSelectedIndex(8);//Fixed.
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.