access to variable within inner class in java(访问java内部类中的变量)
问题描述
我正在尝试创建一个 JLabels 数组,单击时它们都应该不可见.当试图通过需要访问用于声明标签的循环的迭代变量的内部类来设置鼠标侦听器时,就会出现问题.代码不言自明:
I'm trying to create an array of JLabels, all of them should go invisible when clicked. The problem comes when trying to set up the mouse listener through an inner class that needs access to the iteration variable of the loop used to declare the labels. Code is self-explanatory:
for(int i=1; i<label.length; i++) {
label[i] = new JLabel("label " + i);
label[i].addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
label[i].setVisible(false); // compilation error here
}
});
cpane.add(label[i]);
}
我认为我可以通过使用 this
或者 super
而不是调用 label[i]
来克服这个问题内部方法,但我一直无法弄清楚.
I thought that I could overcome this by the use of this
or maybe super
instead of the call of label[i]
within the inner method but I haven't been able to figure it out.
编译错误是:局部变量i是从内部类中访问的;需要声明为final`
The compilation error is: local variable i is accessed from within inner class; needs to be declared final`
我确定答案一定是我没有想到的非常愚蠢的事情,或者我犯了一些小错误.
I'm sure that the answer must be something really silly I haven't thought of or maybe I'm making some small mistake.
任何帮助将不胜感激
推荐答案
您的局部变量必须是 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.
<小时>
资源:
- JLS - 内部类和封闭实例
这篇关于访问java内部类中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:访问java内部类中的变量


基础教程推荐
- 从 python 访问 JVM 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01