How to use PauseTransition method in JavaFX?

前端 未结 2 758
别那么骄傲
别那么骄傲 2020-12-06 14:26

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条回答
  • 2020-12-06 14:38

    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.

    0 讨论(0)
  • 2020-12-06 14:45

    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(); 
    
    0 讨论(0)
提交回复
热议问题