I have coded a countdown timer in java. It counts down from whatever number a user selects in a combo box, there are 3 of them (hour, minute, second). This part is working perfectly fine.
The issue comes when I press my "Reset" button. It clears the labels I use to display the time left, and makes them display "00". But when I press start again, it recalls where it last was in terms of seconds left and starts there.
Please help!!
Here is my code for the timer:
private void JButtonActionPerformed(java.awt.event.ActionEvent evt) {
timer = new Timer(1000, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
onoff = true;
if(hours == 1 && min == 0 && sec ==0){
repaint();
hours--;
lblHours.setText("00");
min=59;
sec=60;
}
if(sec == 0 && min <= 59 && min>0){
sec=60;
min--;
lblHours.setText("00");
}
if(sec == 0 && hours == 0 && min<=0){
repaint();
JOptionPane.showMessageDialog(rootPane, "You have run out of time and did not manage to escape!", "Time is up!!", 0 );
hours = 0; min = 0; sec = 0;
timer.stop();
}
else{
sec--;
repaint();
if (sec<10){
lblSeconds.setText("0"+sec);
repaint();
flag = false;
}
if (hours==0){
repaint();
lblHours.setText("00");
if (min<10)
repaint();
lblMinutes.setText("0"+min);
if (sec<10)
lblSeconds.setText("0"+sec);
else
lblSeconds.setText(""+sec);
}
if(flag){
lblHours.setText(""+hours);
lblMinutes.setText(""+min);
lblSeconds.setText(""+sec);
repaint();
}
}
}
});
timer.start();
}
And my code for the reset button is here:
onoff =false;
timer.stop();
repaint();
lblHours.setText("00");
lblMinutes.setText("00");
lblSeconds.setText("00");
repaint();
I know I go a bit crazy with the repaint(); but I have no idea how often I am meant to use it lol.
Any help/guidance would be greatly appreciated.
See Question&Answers more detail:os