我有一些代码可以做到这一点:
-
创建操作侦听器
a. 从将要连接到的按钮中删除自身(请参阅 2)。
二.做一些其他事情
-
将该操作侦听器添加到按钮
(在代码中:)
ActionListener playButtonActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
playButton.removeActionListener(playButtonActionListener);
// does some other stuff
}
};
playButton.addActionListener(playButtonActionListener);
在编译时,Java 将第 4 行报告为错误(variable playButtonActionListener might not have been initialized)
并拒绝编译。 这可能是因为playButtonActionListener在技术上直到右括号才完全初始化,并且removeActionListener(playButtonActionListener)
需要在playButtonActionListener初始化后进行。
有什么办法可以解决这个问题吗? 我必须完全改变我写这个块的方式吗?还是有某种@
标志或其他解决方案?
更改
playButton.removeActionListener(playButtonActionListener);
跟:
playButton.removeActionListener(this);
由于您位于 ActionListener 匿名类中,因此this
表示该类的当前实例。
您要删除的对象是侦听器本身,因此您可以通过 this
访问它:
ActionListener playButtonActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
playButton.removeActionListener(this);
// does some other stuff
}
};
playButton.addActionListener(playButtonActionListener);