javafx:当到达0时如何停止时间线倒计时计时器

jchrr9hc  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(457)

我有一个代码,显示从10向下倒计时:

但是,在达到0之后,它继续计数为负数。到达零点后如何停止?以便标签上显示的最后一个文本 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
                    }

如果block给出

ERROR: variable timeline might not have been initialized

错误

c6ubokkw

c6ubokkw1#

尝试在时间轴初始化后添加关键帧,而不是在构造函数中添加关键帧。

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)));

相关问题