Reputation: 13
I'm writing a simple game application in JavaFX and am trying to implement a restart game function. My initial thought was to take the gameView pane, remove its children, and then re-add clean ones. For some reason, this doesn't work. Is there another method for adding/removing children to a pane in scene after the stage is already shown?
Start method:
public void start(Stage primaryStage) {
guessedLetters = new ArrayList<>();
wrongGuesses = new ArrayList<>();
gameView = getPane();
primaryStage.setTitle("Hangman");
Scene scene = new Scene(gameView);
primaryStage.setScene(scene);
//primaryStage.setResizable(false);
primaryStage.show();
primaryStage.setMinHeight(scene.getHeight());
primaryStage.setMinWidth(scene.getWidth());
primaryStage.sizeToScene();
}
Reset logic:
private void reset() {
numMistakes = 0;
guessedLetters.clear();
wrongGuesses.clear();
gameView.getChildren().clear();
gameView = getPane();
// ToDo: figure out how to reset pane
}
getPane() initializes and returns new gameView pane:
private BorderPane getPane() {
// Text-input section
lblInput = new Label("Guess a letter: ");
tfInput = new TextField();
tfInput.setOnAction(e -> play());
guessInput = new HBox();
guessInput.getChildren().addAll(lblInput, tfInput);
guessInput.setAlignment(Pos.CENTER);
gallows = new Gallows();
gameBoard = buildGameBoard();
centerScreen = new VBox();
centerScreen.getChildren().addAll(gallows, gameBoard, guessInput);
centerScreen.setSpacing(10);
centerScreen.setAlignment(Pos.CENTER);
centerScreen.setPadding(new Insets(5, 5, 5, 5));
lblOutput = new Label();
lblOutput.setFont(Font.font("Georgia", 15));
gameView = new BorderPane();
gameView.setCenter(centerScreen);
gameView.setBottom(lblOutput);
BorderPane.setAlignment(lblOutput, Pos.CENTER);
return gameView;
}
If not, what other methods of resetting a scene in a window (without opening a new window) are available?
Any suggestions are appreciated.
Upvotes: 0
Views: 150
Reputation: 718
Try this
Stage stage = (Stage) gameView.getScene().getWindow();
gameView = getPane();
stage.setScene(gameView);
Side question: Why does getPane
return gameView
even though it seems that gameView
is a member variable rather than a local variable of that method?
Upvotes: 0