在java中访问内部类的变量 [英] access to variable within inner class in java

查看:169
本文介绍了在java中访问内部类的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个JLabels数组,所有这些都应该在单击时看不见。当尝试通过需要访问用于声明标签的循环的迭代变量的内部类来设置鼠标监听器时,会出现问题。代码不言自明:

  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); //这里编译错误
}
});
cpane.add(label [i]);
}

我以为我可以通过使用 或可能 super 而不是内部的 label [i] 的调用方法,但是我无法弄清楚。



编译错误是:局部变量我从内部类中访问;需要被宣布为final'



我确信答案必须是真的很傻,我没想到,也许我犯了一些小错误。 / p>

任何帮助将不胜感激

解决方案

您的局部变量必须 final 可以从内部(和匿名)类访问。



您可以更改代码,如下所示: (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); //此处不再有编译错误
}
});
label [i] = currentLabel;
}

从JLS:


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



在内部类中使用但未声明的任何本地变量必须明确分配(§16)在内部人的身体之前。




< hr>

资源:




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]);
    }

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.

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.

Any help would be appreciated

解决方案

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;
}

From the JLS :

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

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


Resources :

这篇关于在java中访问内部类的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆