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内部类中的变量
基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01