如何在JavaFX中使用PauseTransition方法? [英] How to use PauseTransition method in JavaFX?

查看:604
本文介绍了如何在JavaFX中使用PauseTransition方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了这本书,但我仍然对暂停转换方法感到困惑。
我做了一个显示数字的标签,我希望这个数字每秒都增加。

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.

推荐答案

如何使用PauseTransition

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();

为什么PauseTransition不适合你

但这不是你想要做的。根据您的问题,您希望每秒更新标签,而不仅仅是一次。您可以将暂停转换设置为无限循环,但这对您没有帮助,因为您无法在JavaFX 8中的循环完成时设置事件处理程序。如果PauseTransition无限循环,则永远不会调用转换的完成处理程序因为过渡永远不会完成。所以你需要另一种方法来做这件事...

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...

你应该使用时间轴

由Tomas Mikula建议的 ,使用时间表而不是PauseTransition。

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();

带定时器的替代解决方案

基于计时器,用于以下问题:

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

但是,我更喜欢基于时间轴的解决方案来解决该问题的定时器解决方案。 Timer需要一个新的线程,并且要特别注意确保在JavaFX应用程序线程上进行更新,而基于时间轴的解决方案不需要任何更新。

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.

这篇关于如何在JavaFX中使用PauseTransition方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆