Hi Im working on a timer program that counts down from 6:00 minutes. 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.
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.