我在 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/