如何使用 PauseTransition
A 暂停转换 http://docs.oracle.com/javase/8/javafx/api/javafx/animation/PauseTransition.html是为了暂时停顿。以下示例将在一秒暂停后更新标签的文本:
label.setText("Started");
PauseTransition pause = new PauseTransition(Duration.seconds(1));
pause.setOnFinished(event ->
label.setText("Finished: 1 second elapsed");
);
pause.play();
为什么 PauseTransition 可能不是您的最佳答案
根据您的问题,您希望每秒更新标签,而不仅仅是一次。
您可以重复运行 PauseTransition,请参阅c0der的回答 https://stackoverflow.com/a/45559673/1155209。这涉及在处理程序内重放转换。
你应该使用时间轴
这是我在 JavaFX 线程上重复执行的首选解决方案。
As 托马斯·米库拉建议 http://tomasmikula.github.io/blog/2014/06/04/timers-in-javafx-and-reactfx.html, use a Timeline http://docs.oracle.com/javase/8/javafx/api/javafx/animation/Timeline.html而不是 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();
使用计时器的替代解决方案
有一个基于的替代解决方案Timer https://stackoverflow.com/questions/16128423/how-to-update-the-label-box-every-2-seconds-in-java-fx对于以下问题:
- 如何在java fx中每2秒更新一次标签框? https://stackoverflow.com/questions/16128423/how-to-update-the-label-box-every-2-seconds-in-java-fx
但是,我更喜欢基于时间线的解决方案而不是该问题中的计时器解决方案。计时器需要一个新线程并额外注意确保 JavaFX 应用程序线程上发生更新。基于时间线的解决方案不需要任何这些。
没有解决办法:设置cycleCount
暂停过渡时
pauseTransition.setCycleCount(Animation.INDEFINITE) https://openjfx.io/javadoc/17/javafx.graphics/javafx/animation/Animation.html#cycleCountProperty行不通。这样,暂停转换将循环无限期地 https://openjfx.io/javadoc/17/javafx.graphics/javafx/animation/Animation.html#INDEFINITE。这对您没有帮助,因为您无法在 JavaFX 17 中设置循环完成时的事件处理程序。
如果 PauseTransition 无限期循环,则永远不会调用转换的完成处理程序,因为转换永远不会完成。
Related
- JavaFX 的延迟任务和周期性任务。 https://stackoverflow.com/questions/9966136/javafx-periodic-background-task/60685975#60685975