Filip Markoski
Filip Markoski

Reputation: 333

JavaFX - Can't cancel timer

The problem I am having is that every time I press the "Single Player" button, which starts the game of Snake, a new instance of the GameTimer class initializes, the problem is that when I click the "Back" button the stopTimer method doesn't manage to cancel or stop the timer and it just ignores it. The timer features works well, but it's highly ineffective and simply said stupid.

Problem: stopTimer() method doesn't cancel the timer.

Here is my project on github: https://github.com/AquaSolid/JavaFX_Snake/blob/master/src/Snake/GameTimer.java

...code omitted..  
public void stopTimer() {
    timerTask.cancel();
    timer.cancel();
    timer.purge();

    isActive = false;
} ...code omitted..  

Upvotes: 0

Views: 1831

Answers (1)

Andrey Lebedenko
Andrey Lebedenko

Reputation: 1988

That bit of your code works perfectly. However:

  1. You don't reset counter of seconds to zero when you stop timer. That's why it appears that timer is constantly running.
  2. You don't actually stop your main game thread, so it runs and runs and runs in the background, resetting game board over and over again.
  3. Make sure you use volatile variables or/and synchronization for multi-threaded classes.
  4. Make sure you know which of the actionBackToMenu is called as button action method.
  5. Don't use same debug messages in more than one place (e.g. "Back To Menu From Instructions")
  6. It is not safe to refer to the button (or actually any visual element) during it's destruction phase.

This will produce NullPointerException in some cases:

Stage stage = (Stage) buttonBackToMenu.getScene().getWindow();

This will work:

Node target = (Node) event.getTarget();
Stage stage = (Stage) target.getScene().getWindow();
  1. Or actually -- zero: Use design patterns. Especially during training (when you have all the time in the Universe).

Good luck.

P.s. I can upload the fixed version to Git if you want.

Upvotes: 2

Related Questions