简体   繁体   English

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

[英]Timer having difficulty when decreasing in minutes

Hi Im working on a timer program that counts down from 6:00 minutes. 嗨我正在研究一个从6点钟开始倒计时的计时器程序。 it works well (6:00, 5:59, 5:58... 5:01, 5:00, 4:59) but then after 4:59 it starts decreasing in minutes and not seconds (ex: 4:59, 3:59, 2:59) and I cant figure out why. 它运作良好(6:00,5:59,5:58 ...... 5:01,5:00,4:59),但随后在4:59之后开始减少,而不是几秒钟(例如:4:59) ,3:59,2:59)我无法弄清楚原因。

Heres the code: 下面是代码:

//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();
        }
    }
}
 if(counter < 0){
       int counter = 59;//change this to

counter = 59;

you are creating another counter variable, which scope will be in the if loop only 您正在创建另一个计数器变量,该范围仅在if循环中

instead you should reset previously(already) declared variable 相反,你应该重置以前(已经)声明的变量

the next time your loop is getting executed, the counter value will not be the one you expected by assigning it to 59 下次循环执行时,计数器值将不是您将其分配给59时所期望的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM