簡體   English   中英

倒數計時器不想在Java中停止

[英]Countdown timer do not want to stop in java

我正在嘗試使用Java與Netbeans 8.1 IDE一起創建倒數計時器,我的問題是,當計時器為00:00時,它不想停止。我試圖編寫timer.stop();。 但它仍然不起作用...也許你可以幫助我..

這是我的源代碼:

 ActionListener action;
    action = new ActionListener() {  
        public void actionPerformed(ActionEvent e) {
           seconds--;

            if(seconds==0){
                minutes--;
                seconds=60;

            }
            if(seconds==0 && minutes==0){
                timer.stop();
            }

            String min = minutes <= 9? "0"+minutes:minutes+"";
            String seg = seconds <= 9? "0"+seconds:seconds+"";

            txtRemaining.setText(min+":"+seg);
        }

    };  
    this.timer = new Timer(interval, action);  
   this.timer.start();

您的問題在這里:

if(seconds==0 && minutes==0){
    timer.stop();
}

因為在您調用此代碼塊之前,秒數永遠不能 == 0:

if(seconds==0){
    minutes--;
    seconds=60;
}

如果seconds == 0,則將其立即設置為60。解決方案是交換這兩行:

// call this **first**
if(seconds==0 && minutes==0){
    timer.stop();
}

// call this **second**
if(seconds == 0){
    minutes--;
    seconds = 60;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM