Timer timer = new Timer();
TimerTask task = new TimerTask(){
public void run(){
for (int i = 0; i <= 30; i++){
lblTimer.setText("" + i);
}
}
};
timer.scheduleAtFixedRate(task, 0, 1000); //1000ms = 1sec
我创建了一个计时器,当我按下按钮时启动,上面是运行的代码。任何人都可以帮我创建一个数到30的计时器吗?现在,当我运行它时,在标签中设置文本“30”,但我希望它从0开始并计数到30。
答案 0 :(得分:5)
每次定时器运行时,它都会执行0到30之间的循环,因此只有在循环结束时才会刷新UI。您需要将i保留在成员中,并在每次调用run
方法时更新它:
Timer timer = new Timer();
TimerTask task = new TimerTask(){
private int i = 0;
public void run(){
if (i <= 30) {
lblTimer.setText("" + i++);
}
}
};
timer.scheduleAtFixedRate(task, 0, 1000); //1000ms = 1sec
当然,一旦你达到i = 30,你应该取消你的时间,否则它会每秒都运行但没有真正的效果或需要。
答案 1 :(得分:1)
问题是,每次执行TimerTask时,你都会直接计数到30.因此每次都会计数到30。你想做的是让i变量在当前时间存储在TimerTask之外,并且每次执行TimerTask时都将它递增1。
这看起来像这样:
TimerTask task = new TimerTask(){
// initially set currentTime to 0
int currentTime = 0;
public void run(){
// only increment if currentTime is not yet 30, you could also stop the timer when 30 is reached
if (currentTime < 30) {
// increment currentTime by 1 and update the label
currentTime++;
lblTimer.setText("" + i);
}
}
};