gpt4 book ai didi

java - ActionListener 中的 Checkystyle 问题 : Reference to instance variable 'x' needs 'this.' in Java

转载 作者:行者123 更新时间:2023-12-02 03:11:29 24 4
gpt4 key购买 nike

首先我是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()因为我在另一个对象(ActionListener)内。

有什么想法如何将 myClass 引用放入 actionListener 中吗?

最佳答案

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

关于java - ActionListener 中的 Checkystyle 问题 : Reference to instance variable 'x' needs 'this.' in Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40984311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com