Alex Yuan
Alex Yuan

Reputation: 35

Pause AnimationTimer JavaFX

I am making a game right now using JavaFX. I was just wondering how can I pause the Animation timer. I what to press a key on the keyboard and the timer pauses and if pressed again it will resume. Is it possible to do so? Thanks in advance.

I have tried using timer.stop() and timer.start() again after but the timer only stops and never start again.

gameScene.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {

        @Override
        public void handle(KeyEvent t) {
            if(t.getCode()== KeyCode.ESCAPE)
            {
                if(!pause){
                    pause = true;
                    timer.start();
                }
                if(pause){
                    pause = false;
                    timer.stop();
                }

            }
        }
    });

Upvotes: 0

Views: 1643

Answers (1)

Slaw
Slaw

Reputation: 45726

You're using consecutive if statements where if the first one executes then the second one will execute, no exceptions. Take a look at your code:

if(!pause){
    pause = true;
    timer.start();
}
if(pause){
    pause = false;
    timer.stop();
}

When pause is false the first if block is executed which sets pause to true and starts the timer. This makes the condition of the second if block evaluate to true, which leads to pause be set back to false and the timer being stopped. In other words, you're starting and then immediately stopping the timer. Note it doesn't matter what the initial value of pause is, since pause will be false after the above code runs at least once (because of the second if block).

Since there's only two possible states for a boolean, and you want to toggle between the two, just use a simple if-else:

if (paused) {
  paused = false;
  timer.start();
} else {
  paused = true;
  timer.stop();
}

Upvotes: 1

Related Questions