Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PauseTransition method in JavaFX?

Tags:

javafx

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.

like image 760
Rin Avatar asked May 30 '15 07:05

Rin


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 is not for you

But this isn't what you want to do. According to your question, you want to update the label every second, not just once. You could set the pause transition to cycle indefinitely, but that wouldn't help you because you can't set an event handler on cycle completion in JavaFX 8. If a PauseTransition is cycled indefinitely, the finish handler for the transition will never be called because the transition will never finish. So you need another way to do this...

You should use a Timeline

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:

  • How to update the label box every 2 seconds in java fx?

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, and the Timeline based solution does not require any of that.

like image 125
jewelsea Avatar answered Oct 19 '22 18:10

jewelsea


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(); 
like image 25
c0der Avatar answered Oct 19 '22 16:10

c0der