内部类的局部变量必须是最终的或有效的最终

时间:2017-05-31 14:55:07

标签: java

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
            }
        });
    }

我已经尝试过了:

final JComboBox[] ChooseType = new JComboBox[a];

我还试图创建一个内部类和一个方法,所以我不必直接处理actionPerformed中的JComboBox。 有人能告诉我如何解决它吗?

2 个答案:

答案 0 :(得分:0)

问题在于b变量。您可以使用临时变量:

for (int b = 0; b < a; b++) {
  int b0 = b;
  chooseType[b] = new JComboBox(Types);
  //...
  chooseType[b0].setSelectedIndex(8);//Error here

ps:我已经改变了变量的大小写以匹配Java的约定。

答案 1 :(得分:0)

简单地将其放入代码中:

    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.
            }
        });
    }