我需要在我的应用程序中实现一个计时器,它将从 10 秒到 0 秒进行倒计时。
并在 JLabel
中显示倒计时。
这是我的实现;
...
Timer t = new Timer(1000, new List());
t.start();
}
class List implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
int sec = 0;
label.setText(""+sec);
// Do a if- condition check to see if the clock has reached to, and then stop
}
}
我原以为 JLabel 会从 0 - 10 开始计数,然后停止。但事实并非如此。 JLabel 设置值 0
并且它不会递增。
更新 1
t = new Timer(1000, new Listner());
t.start();
}
class Listner implements ActionListener{
private int counter = 0;
@Override
public void actionPerformed(ActionEvent e) {
lable.setText(""+ (counter++));
if (counter == 10)
t.removeActionListener(this);
}
}
最佳答案
你没有在任何地方存储或递增 secs
所以我不知道它应该如何更新,试试
Timer timer;
void start() {
timer = new Timer(1000,new List());
}
class List implements ActionListener {
private counter = 0;
@Override
public void actionPerformed(ActionEvent e) {
label.setText(""+counter++);
if (counter == 10)
timer.removeActionListener(this);
}
}
请注意,您需要在某处存储对计时器的引用,以便能够在倒计时结束后从中删除监听器。
关于java - 显示倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13805569/