java - 在 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”。
解决方案
作为Timeline
继承自Animation
,您可以使用setOnFinished
定义在时间线末尾发生的动作。
timeline.setCycleCount(6);
timeline.play();
timeline.setOnFinished(event -> countdownLabel.setText("COUNTDOWN FINISHED"));
推荐阅读
- python-3.x - 熊猫嵌套 JSON - id 作为列名,值作为值
- google-maps - 谷歌地图在我的 HTML 网站中不起作用。API 问题?还是坏代码?
- android - Android - 与 Laravel API 的通信
- python - 我在将变量放入路径时遇到了一些问题
- javascript - 来自 json 对象的 setState 给出未定义的 [React]
- sql - 如何从 SQLServer 获取所有可用数据
- java - 按顺序从属性文件中提取值?
- reactjs - 无法使用命令 react-native run-android 启动应用程序
- java - Maven/Gradle 为编译设置环境变量?
- excel - VBA中的文本到列