java - JavaFX:达到零时如何停止时间轴倒数计时器
问题描述
我有这段代码显示从 10 向下倒计时:
然而,它在达到零后继续计数为负数。达到零后如何停止它?这样标签上要显示的最后一个文本是0
.
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.util.Duration;
public class TestCountdown extends Application {
private GridPane gridPane;
private Scene scene;
private Button button = new Button("Start");
private CountdownTimer timer = new CountdownTimer();
@Override
public void start(Stage applicationStage) {
gridPane = new GridPane();
scene = new Scene(gridPane);
gridPane.add(timer, 0, 1);
gridPane.add(button, 0, 2);
timer.setStyle("-fx-font-size: 50;");
button.setStyle("-fx-font-size: 50;");
button.setOnAction(actionEvent -> timer.start());
applicationStage.setScene(scene);
applicationStage.setFullScreen(true);
applicationStage.show();
}
}
class CountdownTimer extends Label {
private int i = 10;
private boolean started;
public CountdownTimer() {
setText("10");
}
public void start() {
if (started) {
return;
}
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0),
event -> {
setText(String.valueOf(i--));
if (i <= 0) {
timeline.stop(); //ERROR: variable timeline might not have been initialized
}
}),
new KeyFrame(Duration.seconds(1)));
timeline.setOnFinished(event -> System.out.println("Done!"));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
started = true;
}
}
编辑:
编辑:上面的代码已更新:
if (i <= 0) {
timeline.stop(); //ERROR: variable timeline might not have been initialized
}
如果块给出
ERROR: variable timeline might not have been initialized
错误
解决方案
不要在构造函数中添加,而是在 Timeline 初始化后尝试添加 KeyFrames。
Timeline timeline = new Timeline();
KeyFrame kf = new KeyFrame(Duration.seconds(0),
event -> {
setText(String.valueOf(i--));
if (i <= 0) {
timeline.stop();
}
});
timeline.getKeyFrames().addAll(kf, new KeyFrame(Duration.seconds(1)));
推荐阅读
- regex - 如何将可选字符串组合在一起
- angular - ng2-Chart 不适用于新创建的 Angular 10 项目
- cmake - 如何在 CMake 中生成干净(准备发布)的构建?
- python - AWS 中实例的元数据并提供 json 格式的输出
- f# - F#将比较添加到从元组列表中提取元素的递归函数
- python - 为什么 min 和 max 被列为序列操作?
- node.js - oAuth 在前端还是服务器端?
- reactjs - React 'toggleBurgerMenu' 未定义 no-undef
- git - 按日期将分支 DEVELOP 合并到分支 master 中?
- ios - 在 iOS 中重新采样音频