【发布时间】:2018-08-27 10:36:19
【问题描述】:
我在 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;
(此解决方案不会更新倒计时。)
编辑 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”。
【问题讨论】:
-
请提供一个minimal reproducible example 来说明问题。
-
我添加了一个 MCVE 以使其更清晰。
-
good :) 只是(与您的问题无关):请学习 java 命名约定并遵守它们
-
您只是错误地使用了时间线,正如答案中已经解释的那样。您为什么不采纳这些建议并向我们展示为什么它们不符合您的要求?