java - 在 JavaFX 时间轴完成后返回一个值

标签 java javafx timeline

我在 JavaFX 中使用时间轴对 Label 进行倒计时:

timeline.setCycleCount(6);
timeline.play();

我想在时间线结束后返回一个值:

return true;

但是,该值似乎立即返回并且时间线并行运行。如何在不阻塞时间线的情况下等到时间线完成倒计时然后返回值?

编辑:

为了更清楚,我已经尝试过:

new Thread(() -> {
    timeline.play();
}).start();

while(!finished){ // finished is set to true, when the countdown is <=0

}
return true;

(This solution doesn't update the countdown.)

编辑 2:

这是一个最小的、完整的和可验证的例子:

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;


public class CountdownTest extends Application {

    private Label CountdownLabel;
    private int Ctime;

    @Override
    public void start(Stage primaryStage) {

        CountdownLabel=new Label(Ctime+"");

        StackPane root = new StackPane();
        root.getChildren().add(CountdownLabel);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Countdown Test");
        primaryStage.setScene(scene);
        primaryStage.show();

        Ctime=5;

        if(myCountdown()){
            CountdownLabel.setText("COUNTDOWN FINISHED");
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

    public boolean myCountdown(){
         final Timeline timeline = new Timeline(
                            new KeyFrame(
                                    Duration.millis(1000),
                                    event -> {
                                    CountdownLabel.setText(Ctime+"");
                                    Ctime--;

                                    }

                            )
                    );
         timeline.setCycleCount(6);
         timeline.play();
    return true;
    }

}

你可以看到它首先显示“COUNTDOWN FINISHED”并倒计时到0,而不是从倒计时开始倒计时到“COUNTDOWN FINISHED”。

最佳答案

作为 Timeline继承自Animation,你可以使用setOnFinished定义在时间线结束时发生的操作。

timeline.setCycleCount(6);
timeline.play();
timeline.setOnFinished(event -> countdownLabel.setText("COUNTDOWN FINISHED"));

关于java - 在 JavaFX 时间轴完成后返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52037435/

相关文章:

Java - 地址已在使用中(网络绑定(bind))

java - 为什么虎书的符号表中要字符串intern?

java - 与主键、数据类型映射相关的Azure离线sqlite存储同步问题

JavaFX 时间线监听器

video - 阅读嵌入 Youtube 视频时间轴上的当前位置

java - CouchBase 与 Memcached 混合,失去了大多数 CouchDB 理念和功能?

JavaFX:如何在 XY 线图的 Y 轴上正确实现 `getValueForDisplay()`?

java - 调用 setGridLinesVisible(true) 时,GridPane 布局调试行未按预期显示

java - 修剪文件名以用作字符串的正确方法?

java - 不断检查时间线是否停止 - 触发操作