在我的主要课程中:
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变量数字来显示标签 numberLabel 经过的时间。但我无法访问计时器内的最终int变量,错误说:
“无法分配最终的局部变量号,因为它是在封闭类型中定义的”
我知道我可以使用run()中的numberLabel.setText()直接更新标签但是我需要数字变量进行一些时间计算。如何更新数字变量?谢谢
答案 0 :(得分:4)
您应该将number声明为类字段,而不是方法的本地变量。这样它就不需要是最终的,可以在匿名内部类中使用。
我建议不要将它设置为静态,并且不要在静态环境中使用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应用程序(你没说),那么在Swing事件线程EDT(事件调度线程)上运行Timer会反复运行代码。当Swing Timer执行此操作时,java.util.Timer不会执行此操作。
答案 1 :(得分:1)
您无法更新声明为final
的字段。另一方面,您需要将其声明为final才能在内部类中使用它。在进行多线程处理时,您可能希望使用final java.util.concurrent.atomic.AtomicInteger number;
代替。这允许通过set()
中的TimerTask
以及基本线程安全进行分配。