计时器在几分钟内减少时有困难

时间:2014-04-29 23:36:56

标签: java timer

嗨,我正在研究一个从6点钟开始倒计时的计时器程序。它运作良好(6:00,5:59,5:58 ...... 5:01,5:00,4:59),但随后在4:59之后开始减少,而不是几秒钟(例如:4:59) ,3:59,2:59)我无法弄清楚原因。

下面是代码:

//Drag Button
public class event implements ActionListener {
    public void actionPerformed(ActionEvent e){
    int count = 60;
    dragTimer.setText("6:00");
    TimeClass tc = new TimeClass(count);
    dragT = new Timer(1000, tc);
    dragT.start();
    }
}
public class TimeClass implements ActionListener {
    int counter = 60;
    int minute = 5;
    public TimeClass(int counter){
        this.counter = counter;
    }
    public void actionPerformed(ActionEvent tc){
        counter--;
        if(minute > 0){
            if(counter >= 0) {
                String countString = Integer.toString(counter);
                String minuteString = Integer.toString(minute);
                String numb = minuteString + ":" + countString;
                dragTimer.setText(numb);
            }
            if(counter < 10 || counter <= 1){
                String countString = Integer.toString(counter);
                String minuteString = Integer.toString(minute);
                String numb = minuteString + ":0" + countString;
                dragTimer.setText(numb);
            }
            if(counter < 0){
                int counter = 59;
                minute--;
                String countString = Integer.toString(counter);
                String minuteString = Integer.toString(minute);
                String numb = minuteString + ":" + countString;
                dragTimer.setText(numb);
            }
        }else{
            dragT.stop();
            dragTimer.setText("0:00");
            Toolkit.getDefaultToolkit().beep();
        }
    }
}

1 个答案:

答案 0 :(得分:3)

 if(counter < 0){
       int counter = 59;//change this to

counter = 59;

您正在创建另一个计数器变量,该范围将仅在if循环中

相反,您应该重置先前(已经)声明的变量

下次循环执行时,计数器值将不是您将其分配给59所期望的值