Skip to content
Advertisement

How to restart a timer in JavaFX?

I’m currently working on a program in which users can create their on time intervals for different exercises. Once start is pressed, the countdown begins for the first exercise. Once it is done, a sound is played and countdown begins for the second one and so on until all the exercises are done and removed. I use a timer which after every 1 second, subtracts the time of the exercise by 1. The problem is, I can’t seem to find a way to restart Timers in java. When all exercises are done I can stop the timer but I can’t seem to find a way to restart it for when I want to create new exercises and go through the process again. I can’t also find a way to pause and play the timer again during a particular process. I’m new to JavaFX, so I would really appreciate if you could guide me how I can change my code to achieve what I’m looking for.

JavaScript

Advertisement

Answer

Since the Timer does nothing except track time it would be better to use the javafx.animation API. This gives you certain advantages:

  • Everything happens on the JavaFX Application Thread, meaning no concurrency issues.
  • You can make use of the currentTime and cycleDuration properties of Animation to track the time left in the countdown.
  • You can make use of the play(), pause(), and stop() methods of Animation to control the timer.
  • You can use the onFinished property of Animation to play you sound when the timer completes.

Here’s an example using PauseTransition, though you could also use e.g. Timeline.

JavaScript

Side note: You mention a sound is played when the timer completes, and I can see a call to mediaPlayer.play(). Considering the nature of the program I assume the sound being played is relatively short. If that’s the case you should consider using AudioClip instead of MediaPlayer.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement