在我的主课中:
public class Main{
public static void main(String[] args) {
//some code
final int number = 0;
numberLabel.setText(number);
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask(){
public void run(){
//elapsed time
number = number + 1;
}
}, 1000, 1000);
}
}
我正在使用最终的 int 变量 number 将耗时显示到标签 numberLabel 中。但是我无法访问计时器内的最终 int 变量,错误说:
“无法分配最终的局部变量编号,因为它是在封闭类型中定义的”
我知道我可以在 run() 中使用 numberLabel.setText() 直接更新标签,但是我需要数字变量来计算一些时间。我如何更新 number 变量?谢谢
最佳答案
您应该将数字声明为类字段,而不是方法的局部变量。这样它就不需要是 final 的,可以在匿名内部类中使用。
我建议不要将它设为静态,并且您不要在静态环境中而是在实例世界中使用您的 Timer。
public class Main{
private int number = 0;
public void someNonStaticMethod() {
//some code
// final int number = 0;
numberLabel.setText(number);
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask(){
public void run(){
//elapsed time
number = number + 1;
}
}, 1000, 1000);
}
}
顺便说一句,您对 numberLabel.setText(...)
的使用表明这将在 Swing GUI 中使用。如果是这样,那么不要使用 java.util.Timer,而应该使用 javax.swing.Timer 或 Swing Timer。
public class Main2 {
public static final int TIMER_DELAY = 1000;
private int number = 0;
public void someMethod() {
numberLabel.setText(String.valueOf(number));
new javax.swing.Timer(TIMER_DELAY, new ActionListener() {
public void actionPerformed(ActionEvent e) {
number++;
numberLabel.setText(String.valueOf(number));
}
}).start();
}
}
同样,如果这是一个 Swing 应用程序(您不会说),那么由 Timer 在 Swing 事件线程 EDT(事件调度线程)上运行的代码重复运行是至关重要的。 java.util.Timer 不执行此操作,而 Swing Timer 执行此操作。
关于Java定时器和定时器任务: Accessing variables outside Timer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19344995/