ActionListener 中的 Checkystyle 问题:对实例变量 'x' 的引用需要 'this.' 在 Java 中

Checkystyle issue in ActionListener: Reference to instance variable 'x' needs 'this.' in Java

起初我是Java的初学者。我对线程标题中提到的 checkstyle 错误有疑问。

考虑使用类似的代码:

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

     }

    }

在构造函数中,我从属性 buttons 为按钮创建了 onclick 事件,单击按钮时它将执行方法 firstMethod(int, int)secondMethod(int, int),当然一切正常,但 checkstyle 抛出错误。 由于某些原因,我不能只使用 this.firstMethod(),因为我在另一个 object(ActionListener)中。

知道如何将 myClass 引用放入 actionListener 中吗?

使用 myClass.this 而不是普通的 this 来引用外部 class 实例。 classes 也使用大写字母,所以 MyClass,而不是 myClass.

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