简体   繁体   中英

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..  

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 (eg "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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM