在我的主类:
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变量,错误说:
“最终的局部变量号码不能被分配,因为它是在封闭类型定义”
我知道我可以更新运行中直接使用numberLabel.setText标签()(),但是我需要一些时间计算数量变量。 如何更新数量变量? 谢谢
你应该申报数量为一类领域,而不是一个局部变量的方法。 这样,它不需要是终局的,可以在匿名内部类中使用。
我认为它不能进行静态和你不是在静态环境,而是在实例世界使用定时器。
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中或摇摆定时器。
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(事件指派线程)。 而摇摆不定时的java.util.Timer中并没有这样做。
您不能更新现场宣布final
。 在另一方面,你需要声明它最终能在一个内部类中使用它。 当你正在做的多线程,你可能想使用一个final java.util.concurrent.atomic.AtomicInteger number;
代替。 这样就可以通过任务set()
在您TimerTask
以及基本的线程安全的。