访问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 - 内部类和封闭实例
相关文章