且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

访问java内部类中的变量

更新时间:2023-02-15 20:14:11

您的局部变量必须是 final 才能从内部(和匿名)类访问.

Your local variable must be final to be accessed from the inner (and anonymous) class.

您可以将代码更改为以下内容:

You can change your code for something like this :

for (int i = 1; i < label.length; i++) {
    final JLabel currentLabel =new JLabel("label " + i); 
    currentLabel.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent me) {
            currentLabel.setVisible(false);   // No more compilation error here
        }
    });
    label[i] = currentLabel;
}

来自 JLS:

任何使用但未在内部类中声明的局部变量、形参或异常参数都必须声明为final.

Any local variable, formal parameter, or exception parameter used but not declared in an inner class must be declared final.

任何使用但未在内部类中声明的局部变量必须明确分配 (§16) 在内部类的主体之前.

Any local variable used but not declared in an inner class must be definitely assigned (§16) before the body of the inner class.

资源: