Search code examples
javajavafxscene

Why is my second scene in JavaFX not showing up?


I have a JavaFX program that is supposed to switch between two scenes, the first works great, but the second scene (scene2) is empty and does not show the button I created, any help would be greatly appreciated!

@Override
public void start(Stage primaryStage) {
    //first scene
    Button btGenerate = new Button("Generate My First Scene!");
    btGenerate.setOnAction((ActionEvent event) -> {primaryStage.setScene(scene2);});

    GridPane gPane = createTextFieldPane();
    gPane.add(btGenerate, 0, 6);
    Scene scene1 = new Scene(gPane, 600, 600);

    //second scene
    Button btReturn = new Button("Make a New Scene!");
    btReturn.setOnAction((ActionEvent event) -> {primaryStage.setScene(scene1);});

    Group root = new Group();
    root.getChildren().add(btReturn);
    Scene scene2 = new Scene(root, 600, 600, Color.LIGHTBLUE);

    primaryStage.setTitle("Switch Scenes!");
    primaryStage.setScene(scene1);
    primaryStage.show();                

}

Solution

  • Just need to move the setOnAction on btGenerate to after declaring the scene 2

        btGenerate.setOnAction(e-> {
            primaryStage.setScene(scene2);
        });
    

    This piece of code should be here:

        Group root = new Group();
        root.getChildren().add(btReturn);
        Scene scene2 = new Scene(root, 600, 600, Color.LIGHTBLUE);
        btGenerate.setOnAction(e-> {
            primaryStage.setScene(scene2);
        });
        primaryStage.setTitle("Switch Scenes!");
        primaryStage.setScene(scene1);
        primaryStage.show();
    

    You were setting an empty scene, that's why is not working.