首页 > 解决方案 > 在 JavaFX 时间轴完成后返回一个值

问题描述

我在 JavaFX 中使用时间线对 a 进行倒计时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;

(此解决方案不会更新倒计时。)

编辑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”。

标签: javajavafxtimeline

解决方案


作为Timeline继承自Animation,您可以使用setOnFinished定义在时间线末尾发生的动作。

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

推荐阅读