Issue
In my code I can switch to another scene using buttons like this:
public void handleButtonClick(MouseEvent event) throws IOException {
Parent menu_parent = FXMLLoader.load(getClass().getResource("/FXML/FXMLmm2.fxml"));
Scene SceneMenu = new Scene(menu_parent);
Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
stage.setScene(SceneMenu);
stage.show();
}
Now I have a method in the controller class which should open a scene without an event:
public void showResult(boolean win) throws IOException {
if (win == true) {
Parent menu_parent = FXMLLoader.load(getClass().getResource("/FXML/FXMLWinScreen.fxml"));
Scene SceneMenu = new Scene(menu_parent);
Stage stage = new Stage();
stage.setScene(SceneMenu);
stage.show();
}
The problem is, I don't know how to get the node for the stage, this program is only working when I open a whole new stage/window.
How can I switch to a new Scene without an events and opening a new stage?
Solution
You can use any @FXML
injected node from your controller class,
Let's say you have a button
@FXML private Button show;
Now use that button show.getParent().getScene().getWindow()
to get the current stage,
public void showResult(boolean win) throws IOException {
if (win == true) {
Parent menu_parent = FXMLLoader.load(getClass()
.getResource("/FXML/FXMLWinScreen.fxml"));
Scene SceneMenu = new Scene(menu_parent);
Stage stage = (Stage)show.getParent().getScene().getWindow();
stage.setScene(SceneMenu);
stage.show();
}
}
But make SURE that showResult
executes after the controller initialization and the node is injected.
Answered By - Shekhar Rai