2016-12-05 26 views
0

起初我是Java的初学者。我在线程标题中提到的checkstyle错误有问题。ActionListener中的Checkystyle问题:引用实例变量'x'需要'this'。在Java中

考虑让similiar代码:

public class myClass { 
    JButton[] buttons; 

     public myClass() { 
     this.buttons = new JButton[2]; 
     //constructor code.... 

     this.buttons[0].addActionListener(new ActionListener() { 
        public void actionPerformed(ActionEvent e) {     
         firstMethod(0, 1); 
         secondMethod(5, 10); 
        } 
       }); 

     } 

     public void firstMethod(int x, int y) { 
     // do something 

    } 

     public void secondMethod(int x, int y) { 
     // do something 

    } 

    } 

在constructior我从属性buttons,在点击按钮时,将执行方法firstMethod(int, int)secondMethod(int, int)创建onclick事件的按钮,当然一切工作,但checkstyle会引发错误。 由于某些原因,我不能只使用this.firstMethod(),因为我在另一个对象(ActionListener)内。

任何想法如何将myClass引用放入actionListener?

+0

可能,但checkstyle错误未在您发布的帖子中提及,因此我没有找到解决方案。 – t4dohx

回答

1

new ActionListener() { ... };块实际上创建了一个新的匿名类。在该块内部,this指的是ActionListener。要引用外部myClass对象,请使用myClass.this

+0

是的,这是我一直在寻找的东西。非常感谢! :) – t4dohx

1

使用myClass.this而不是普通的this来引用外部类实例。也可以使用大写字母,因此MyClass,而不是myClass

+0

是的,我知道,编写快速示例时我犯了一个错误。谢谢你的回答。 – t4dohx