I am creating a Solitaire game using JavaFX. I want a Restart button to start a new game, but also a Reset button that will restart the same game i.e. the same scene to its original state.
Restart works seamlessly as I was able to call the start
method but I am unable to get Reset working.
package guisolitaire;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;
public class GUISolitaire extends Application {
Game game;
Pane root;
ScoreTimer timer = new ScoreTimer();
@Override
public void start(Stage primaryStage) {
Canvas canvas = new Canvas(1000, 800);
root = new Pane(canvas);
root.setStyle("-fx-background-color: green");
game = new Game(canvas.getGraphicsContext2D());
canvas.setOnMouseClicked(game::handleMouseClicked);
timer.restart();
timer.start();
Scene scene = new Scene(root, Color.GREEN);
primaryStage.setScene(scene);
primaryStage.setTitle("Solitaire");
primaryStage.show();
Label l = new Label(); // Timer label
Timeline timeline = new Timeline(
new KeyFrame(Duration.ZERO, ae -> l.setText("Time elapsed: " + timer.s)),
new KeyFrame(Duration.seconds(1))
);
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
l.setTranslateX(800);
l.setTranslateY(765);
root.getChildren().add(l);
Button newGameButton = new Button();
newGameButton.setText("New Game");
newGameButton.setTranslateX(10);
newGameButton.setTranslateY(765);
root.getChildren().add(newGameButton);
EventHandler<ActionEvent> newGameEvent = ae -> {
timer.stop();
timer.restart();
start(primaryStage);
};
newGameButton.setOnAction(newGameEvent);
Button restart = new Button();
restart.setText("Restart");
restart.setTranslateX(100);
restart.setTranslateY(765);
root.getChildren().add(restart);
EventHandler<ActionEvent> resetGameEvent = ae -> {
primaryStage.setScene(scene);
primaryStage.show();
timer.stop();
timer.restart();
};
restart.setOnAction(resetGameEvent);
}
public static void main(String[] args) {
launch(args);
}
}
I have tried to reset primaryStage
with the same scene and call the show
method but that does not restart the game, it does not do anything.
Any ideas on how this may be able to be implemented?