I read the book, but I am still confused about pause transition methods. I made a label showing number, and I want that number to be increased in every second.
2 Answers
How to use a PauseTransition
A PauseTransition is for a one off pause. The following sample will update the text of a label after a one second pause:
label.setText("Started");
PauseTransition pause = new PauseTransition(Duration.seconds(1));
pause.setOnFinished(event ->
label.setText("Finished: 1 second elapsed");
);
pause.play();
Why a PauseTransition may not be the best answer for you
According to your question, you want to update the label every second, not just once.
You can run a PauseTransition repetitively, see c0der’s answer. This involves replaying the transition within the handler.
You should use a Timeline
This is my preferred solution for repetitive execution on the JavaFX thread.
As suggested by Tomas Mikula, use a Timeline instead of a PauseTransition.
label.setText("Started");
final IntegerProperty i = new SimpleIntegerProperty(0);
Timeline timeline = new Timeline(
new KeyFrame(
Duration.seconds(1),
event -> {
i.set(i.get() + 1);
label.setText("Elapsed time: " + i.get() + " seconds");
}
)
);
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
Alternate solution with a Timer
There is an alternate solution based on a Timer for the following question:
However, I prefer the Timeline based solution to the Timer solution from that question. The Timer requires a new thread and extra care in ensuring updates occur on the JavaFX application thread. The Timeline based solution does not require any of that.
Not a solution: setting cycleCount
on a pause transition
pauseTransition.setCycleCount(Animation.INDEFINITE)
won’t work. With this, the pause transition will cycle indefinitely. That won’t help you, because you can't set an event handler on cycle completion in JavaFX 17.
If a PauseTransition is cycled indefinitely, the finish handler for the transition will never be called because the transition will never finish.
Related

- 150,031
- 14
- 366
- 406
-
1To be complete, you can use the PauseTransition if you start it again inside of the finish handler if I'm correct. – Adowrath Feb 11 '17 at 12:57
As commented by Adowarth :
you can use the PauseTransition if you start it again inside of the finish handler
int cycle = 0;
label.setText("Started");
PauseTransition pause = new PauseTransition(Duration.seconds(1));
pause.setOnFinished(event ->
label.setText("Finished cycle " + cycle++);
pause.play();
);
pause.play();

- 18,467
- 6
- 33
- 65