Issue
I have this code that displays count down from 10 downward:
However it continues counting into negative numbers after zero is reached. How do I stop it after zero is reached? So that the last text to be displayed on the label is 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;
}
}
EDIT:
EDIT: Code above is updated:
if (i <= 0) {
timeline.stop(); //ERROR: variable timeline might not have been initialized
}
if-block gives
ERROR: variable timeline might not have been initialized
error
Solution
Instead of adding in constructor, try adding KeyFrames after Timeline is initialized.
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)));
Answered By - Sai Dandem
Answer Checked By - Katrina (JavaFixing Volunteer)