How do I use the PauseTransition method in JavaFX?

I read the book but I am still confused about the pause transition methods. I made a shortcut showing the number and I want the number to increment every second.

+3


source to share


2 answers


How to use PauseTransition

A PauseTransition for one pause. The following sample will update the label text 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 PauseTransition isn't for you

But that's not what you want to do. As per your question, you want to update the shortcut every second, not once. You can set the transition to pause indefinitely, but that will not help you because you cannot set an event handler when the loop ends in JavaFX 8. If the PauseTransition loops endlessly, the exit handler for the transition will never be called because the transition will never will end. So you need another way to do it ...

You must use a timeline



As suggested by Thomas Mikula , use Timeline instead of 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();

      

Alternative solution with timer

There is an alternative Timer based solution for the following question:

However, I prefer Timeline's solution to Timer's solution from this question. The timer requires a new thread and extra care in providing updates to the JavaFX application thread, and the timeline solution requires nothing.

+5


source


As Adowarth commented :

you can use PauseTransition if you run it again inside a trim 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(); 

      

+1


source







All Articles