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.
Timer timer = new Timer();
startButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//Timer task=new TimerTask();
timer.schedule(new TimerTask() {
@Override
public void run() {
running=true;
if (running==true)
{
if (workoutsList.size() == 0) {
return;
}
if (workoutsList.size() == 1 && workoutsList.get(0).time == 1) {
text.setText("over!");
mediaPlayer1.play();
workoutsList.clear();
workouts.getItems().clear();
timer.cancel();
return;
}
workoutsList.get(0).time -= 1;
if (workoutsList.get(0).time == 0) {
workoutsList.remove(0);
mediaPlayer.play();
return;
}
workouts.getItems().clear();
workouts.refresh();
for (int i = 0; i < workoutsList.size(); i++) {
workouts.getItems().add(workoutsList.get(i));
}
}
}
}, 0, 1000);
}
});
stopButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
timer.cancel();
running=false;
}
});