Search code examples
javatimercountdowntimertask

JAVA: start timer, stop timer at 0 seconds, restart timer


The private code is within a Jbutton that starts a timer upon mouse click. The if-statement near the bottom will not stop the timer, when the elapsed time is equal to the original time, but does not. How do I fix this? Additionally, when I repress the button, the timer accelerates at an increased rate.

import java.awt.*;
import java.util.*;


public class refractiveIndex extends javax.swing.JFrame {

public static int time = 10;
public static int elapsedTime = 0;

private void nextQActionPerformed(java.awt.event.ActionEvent evt) { 

time = 10;
elapsedTime = 0;                                     

    final Timer timer = new Timer();
    TimerTask task = new TimerTask()
    {
        public void run()
                {
                    elapsedTime++;//amount of time passed
                    timeLeft.setText("" + (time - elapsedTime));//int 'time' = 0 (this is time left)
                }
    };

    if(time - elapsedTime == 0)
    {
        timer.cancel();//timer stops after 5 secs
        score1 = 0;//resets score
        question.setText("GAME OVER");
    }

    timer.scheduleAtFixedRate(task, 500, 500);//.5 second delay, rate of .5 second

Solution

  • You can adapt your custom TimerTask:

    TimerTask task = new TimerTask() {
        public void run() {
            elapsedTime++;//amount of time passed
            timeLeft.setText("" + (time - elapsedTime));
    
            if (time - elapsedTime == 0) {
                cancel();
                score1 = 0;//resets score
                question.setText("GAME OVER");
            }
        }
    };
    

    See also this question.