【问题标题】:Local variables from a inner class must be final or effectively final内部类的局部变量必须是最终的或有效的最终的
【发布时间】:2017-11-01 10:52:24
【问题描述】:
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。 有人可以告诉我如何解决吗?

【问题讨论】:

标签: java


【解决方案1】:

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

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

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

【讨论】:

  • 就是这么简单。谢谢
【解决方案2】:

简单地把它放在代码中:

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

【讨论】:

    猜你喜欢
    • 2015-01-25
    • 1970-01-01
    • 2022-11-13
    • 2017-08-28
    • 2023-02-19
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多