fwackk
fwackk

Reputation: 97

JavaFX - How to change scene using a scene from another class?

I have the following class which has a button.

public class GUI extends Application {
    private BorderPane mainLayout = new BorderPane();

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Main Menu");

        FlowPane layout = new FlowPane();
        Button button = new Button("Click");
        layout.getChildren().addAll(button);

        mainLayout.setTop(layout);

        Scene scene = new Scene(mainLayout, 600, 600);

        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

If I have another class with a scene, how can I update the GUI class to show the scene by pressing the button?

Upvotes: 4

Views: 12244

Answers (1)

jewelsea
jewelsea

Reputation: 159281

The preferred mechanism would probably be to get the stage dynamically from a trigger event, for example:

button.setOnAction(event -> {
    Scene newScene = // ... commands which define the new scene.
    Stage stage = ((Node) event.getTarget()).getScene().getStage();
    // or alternatively, just:
    // Stage stage = button.getScene().getStage();
    stage.setScene(newScene);
});

An alternative is to provide a static accessor to the main stage in the Application.

Change your GUI class to add an accessor for the stage:

public class GUI extends Application {
    private static Stage guiStage;

    public static Stage getStage() {
        return guiStage;
    }

    @Override
    public void start(Stage primaryStage) {
        guiStage = primaryStage;
        // other app initialization logic . . .
    }
}

In your class which needs to change the scene for the GUI stage to a new scene, invoke:

Scene newScene = // ... commands which define the new scene.
GUI.getStage().setScene(newScene);

Using a static accessor in this specific instance is generally OK, because you can only have a single Application instance launched for a given JVM execution. The only real drawback is that you have a coded dependency between the class creating your new scene and your Application class. But, for some application types, this won't matter.

Upvotes: 5

Related Questions