我正在尝试编写一个静态类,它可以更改控制背景,该控制背景将传递给参数。所以我实现了这个:
public static void wrong(final Component component) {
component.setBackground(Color.RED);
Timer timer = new Timer(2, wrongAction);
wrongAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int green = component.getBackground().getGreen();
int blue = component.getBackground().getBlue();
component.setBackground(new Color(255, green + 1, blue + 1));
if (component.getBackground() == Color.WHITE) {
timer.stop();
}
}
};
timer.start();
}
我遇到了一个错误:
Cannot refer to a non-final variable timer inside an inner class defined in a different method
当然,我们可以将计时器更改为最终计时器,但这样做后方法将停止工作。
我尝试用 google 搜索并在其他 stackoverflow 主题中找到答案,但没有任何帮助。
提前非常感谢大家!
最佳答案
问题是您使用了不同的错误操作引用。
public static void wrong(final Component component) {
component.setBackground(Color.RED);
Timer timer = new Timer(2, wrongAction);// <-- Here wrongAction is not the one you
// define on the next line
wrongAction = new ActionListener() { // <-- This is a new ActionListener but Timer
// has no knowledge about it.
@Override
public void actionPerformed(ActionEvent e) {
int green = component.getBackground().getGreen();
int blue = component.getBackground().getBlue();
component.setBackground(new Color(255, green + 1, blue + 1));
if (component.getBackground() == Color.WHITE) {
timer.stop();
}
}
};
timer.start();
}
下面的代码将立即运行(但我觉得不太干净,最好将所有这些封装在一个专用对象中,以便 Timer 可以成为类的变量并且监听器可以引用它) :
public static void wrong(final Component component) {
class MyActionListener implements ActionListener {
private Timer timer;
public void setTimer(Timer timer) {
this.timer = timer;
}
@Override
public void actionPerformed(ActionEvent e) {
int green = component.getBackground().getGreen();
int blue = component.getBackground().getBlue();
component.setBackground(new Color(255, green + 1, blue + 1));
if (component.getBackground().equals(Color.WHITE)) {
if (timer == null) {
System.err.println("This sucks, I got no timer");
} else {
timer.stop();
}
}
}
}
MyActionListener wrongAction = new MyActionListener();
component.setBackground(Color.RED);
Timer timer = new Timer(2, wrongAction);
wrongAction.setTimer(timer);
timer.start();
}
关于java - 不能引用非最终变量和计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10587316/