1

first of all I'm kinda new to programing, so all help will be appreciated. I got this code in which I used java.util.timer and i would like to restart the timer after a certain button click. The timer will start when I open the game for the first time, after 40 seconds there will a message and all buttons of the game except the "start" and "end" button will be disabled. And now to my question, how can I restart a timer after succesfully cleaned and purged it?

public AntInking_GUI() { 
    timerStart();
}
public void startButton() {
    // start button, re-generates a new pattern and re-news the time
    enableButtons();
    timerStart();
    timerSeconds = 0;
    timeLeft = 40;

public void timerStart() {
    // timer that counts from 40 to 0, if it reaches 0 then the game will
    // end and the buttons will be disabled

    TimerTask task = new TimerTask() {

        public void run() {

            timerSeconds++;
            timeLeft = 40 - timerSeconds;
            changeText();
            if (timerSeconds >= 40) {
                showTextEnd();
                pause();
                gametimer.purge();
                gametimer.cancel();

            }
        }
    };

    if (isGameRunning == false) {

        gametimer.scheduleAtFixedRate(task, 1000, 1000);
        isGameRunning = true;
    }

As you can see the timer will stop , yet I couldn't create a new timer. Thanks in advance!

Nico S.
  • 15
  • 1
  • 4

1 Answers1

3

you have to assign a new instance of a Timer. for example, see below:

import java.util.Timer;
import java.util.TimerTask;

public class Main {
    private static Timer timer;

    public static void main(String[] args) throws InterruptedException {
        Main main = new Main();
        main.launchSomeTimer("john doe");

        Thread.sleep(5000);
        main.resetSomeTimer();

        Thread.sleep(10000);
        timer.cancel();


    }

    private void launchSomeTimer(String name) {
        TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                System.out.println("name: " + name);
            }
        };
        timer = new Timer();
        timer.schedule(timerTask, 500);

    }

    public void resetSomeTimer() {
        TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                System.out.println("updating timer");
            }
        };
        timer.cancel();
        timer = new Timer();
        timer.schedule(timerTask, 1000);

    }
}
Jose Zevallos
  • 685
  • 4
  • 3