2
private void btnGuess1ActionPerformed(java.awt.event.ActionEvent evt) {    
    Timer timer = new Timer();
    TimerTask task = new TimerTask(){
        private int i = 0;
        public void run(){
            if (i <= 20){
                lblTimer.setText("" + i++);
            }
        }
    };
    timer.cancel();
    timer.purge();
    timer = new Timer();
    timer.schedule(task, 1000);

This is what I have so far. When I activate this piece of code using a button, the timer never resets. How can I fix this? There are no error message either.

Any help is appreciated thanks in advance.

Jeffrey Cao
  • 21
  • 2
  • 9

1 Answers1

2

Make timer a member of your class and create it in the constructor. You should be cancelling the timer before scheduling your new task. Something like this:

 private void btnGuess1ActionPerformed(java.awt.event.ActionEvent evt) {    
    timer.cancel();
    TimerTask task = new TimerTask(){
       private int i = 0;
       public void run(){
       if (i <= 20){
         lblTimer.setText("" + i++);
      }
    }
};
timer = new Timer();
timer.scheduleAtFixedRate(task, 0, 1000);
Dakshinamurthy Karra
  • 5,353
  • 1
  • 17
  • 28