简体   繁体   English

JavaFX - 如何使用另一个类的场景更改场景?

[英]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? 如果我有另一个带有场景的类,如何通过按下按钮来更新GUI类以显示场景?

Here is a sample which relies on static accessor to the main stage in the Application. 这是一个依赖于Application中主阶段的静态访问器的示例。

Change your GUI class to add an accessor for the stage: 更改GUI类以添加阶段的访问者:

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: 在您的类中需要将GUI阶段的场景更改为新场景,请调用:

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

Using a static accessor is generally OK, because you can only have a single Application instance launched for a given JVM execution. 使用静态访问器通常是可以的,因为您只能为给定的JVM执行启动单个Application实例。 The only real drawback is that you have a coded dependency between the class creating your new scene and your Application class. 唯一真正的缺点是,在创建新场景的类和Application类之间存在编码依赖关系。 But, for some application types, this won't matter. 但是,对于某些应用程序类型,这无关紧要。


An alternate mechanism to a static accessor is to get the stage dynamically, 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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM