I wanna swap between two Scenes. Like, the first one has a button with the text "Go to Stage 2" and the second one has a button with the text "Go Back". Now, the problem is, I can go to Stage 2 with the Button, but I can't go back. Reason is: "already set as root of another scene". Sounds simple for me but I just don't know how I can fix the problem.
I know that I'm not the first one with the problem but I couldn't find an answer... please send help!
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
BorderPane root1 = new BorderPane();
BorderPane root2 = new BorderPane();
primaryStage.setTitle("Hello World");
Button nextStageButton = new Button("Go to Stage 2");
root1.setCenter(nextStageButton);
nextStageButton.setOnAction((event) -> {
primaryStage.setScene(new Scene(root2, 300, 275));
});
Button backStageButton = new Button("Go Back");
root2.setCenter(backStageButton);
backStageButton.setOnAction((event) -> {
primaryStage.setScene(new Scene(root1, 300, 275));
});
primaryStage.setScene(new Scene(root1, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
I think the exception is very obvious, you are putting the same root in multiple scenes every time you switch the scenes. So you can create your scenes in the beginning and switch between them :
@Override
public void start(Stage primaryStage) throws Exception{
BorderPane root1 = new BorderPane();
BorderPane root2 = new BorderPane();
primaryStage.setTitle("Hello World");
Button nextStageButton = new Button("Go to Stage 2");
root1.setCenter(nextStageButton);
Scene scene1 =new Scene(root1, 300, 275);
Scene scene2 =new Scene(root2, 300, 275);
nextStageButton.setOnAction((event) -> {
primaryStage.setScene(scene2);
});
Button backStageButton = new Button("Go Back");
root2.setCenter(backStageButton);
backStageButton.setOnAction((event) -> {
primaryStage.setScene(scene1);
});
primaryStage.setScene(scene1);
primaryStage.show();
}
or you can create one scene and switch between roots :
@Override
public void start(Stage primaryStage) throws Exception{
BorderPane root1 = new BorderPane();
BorderPane root2 = new BorderPane();
primaryStage.setTitle("Hello World");
Button nextStageButton = new Button("Go to Stage 2");
root1.setCenter(nextStageButton);
Scene scene =new Scene(root1, 300, 275);
nextStageButton.setOnAction((event) -> {
scene.setRoot(root2);
});
Button backStageButton = new Button("Go Back");
root2.setCenter(backStageButton);
backStageButton.setOnAction((event) -> {
scene.setRoot(root1);
});
primaryStage.setScene(scene);
primaryStage.show();
}