我正在尝试创建一个 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.
<小时>
资源:
这篇关于访问java内部类中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何检测 32 位 int 上的整数溢出?How can I detect integer overflow on 32 bits int?(如何检测 32 位 int 上的整数溢出?)
return 语句之前的局部变量,这有关系吗?Local variables before return statements, does it matter?(return 语句之前的局部变量,这有关系吗?)
如何将整数转换为整数?How to convert Integer to int?(如何将整数转换为整数?)
如何在给定范围内创建一个随机打乱数字的 intHow do I create an int array with randomly shuffled numbers in a given range(如何在给定范围内创建一个随机打乱数字的 int 数组)
java的行为不一致==Inconsistent behavior on java#39;s ==(java的行为不一致==)
为什么 Java 能够将 0xff000000 存储为 int?Why is Java able to store 0xff000000 as an int?(为什么 Java 能够将 0xff000000 存储为 int?)