如何在 JavaFX 中使用 PauseTransition 方法?
How to use PauseTransition method in JavaFX?
书看了,但是对暂停过渡的方法还是很迷惑。
我做了一个显示数字的标签,我希望这个数字每秒都在增加。
如何使用暂停过渡
A PauseTransition 用于一次性暂停。以下示例将在暂停一秒后更新标签的文本:
label.setText("Started");
PauseTransition pause = new PauseTransition(Duration.seconds(1));
pause.setOnFinished(event ->
label.setText("Finished: 1 second elapsed");
);
pause.play();
为什么 PauseTransition 不适合你
但这不是你想要做的。根据您的问题,您希望每秒更新一次标签,而不是一次。您可以将暂停过渡设置为无限循环,但这对您没有帮助,因为您无法在 JavaFX 8 中设置循环完成时的事件处理程序。如果无限循环暂停过渡,则永远不会调用过渡的完成处理程序因为过渡永远不会完成。所以你需要另一种方法来做到这一点...
你应该使用时间轴
作为 suggested by Tomas Mikula, use a Timeline 而不是 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 的替代解决方案:
- How to update the label box every 2 seconds in java fx?
但是,我更喜欢基于时间轴的解决方案而不是那个问题的定时器解决方案。 Timer 需要一个新线程并格外小心以确保更新发生在 JavaFX 应用程序线程上,而基于时间轴的解决方案不需要任何这些。
正如 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();
书看了,但是对暂停过渡的方法还是很迷惑。 我做了一个显示数字的标签,我希望这个数字每秒都在增加。
如何使用暂停过渡
A PauseTransition 用于一次性暂停。以下示例将在暂停一秒后更新标签的文本:
label.setText("Started");
PauseTransition pause = new PauseTransition(Duration.seconds(1));
pause.setOnFinished(event ->
label.setText("Finished: 1 second elapsed");
);
pause.play();
为什么 PauseTransition 不适合你
但这不是你想要做的。根据您的问题,您希望每秒更新一次标签,而不是一次。您可以将暂停过渡设置为无限循环,但这对您没有帮助,因为您无法在 JavaFX 8 中设置循环完成时的事件处理程序。如果无限循环暂停过渡,则永远不会调用过渡的完成处理程序因为过渡永远不会完成。所以你需要另一种方法来做到这一点...
你应该使用时间轴
作为 suggested by Tomas Mikula, use a Timeline 而不是 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 的替代解决方案:
- How to update the label box every 2 seconds in java fx?
但是,我更喜欢基于时间轴的解决方案而不是那个问题的定时器解决方案。 Timer 需要一个新线程并格外小心以确保更新发生在 JavaFX 应用程序线程上,而基于时间轴的解决方案不需要任何这些。
正如 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();