首页 > 解决方案 > 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

错误

标签: javajavafx

解决方案


不要在构造函数中添加,而是在 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)));

推荐阅读