簡體   English   中英

JavaFX - 如何使用另一個類的場景更改場景?

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

我有以下類有一個按鈕。

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();
    }
}

如果我有另一個帶有場景的類,如何通過按下按鈕來更新GUI類以顯示場景?

這是一個依賴於Application中主階段的靜態訪問器的示例。

更改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 . . .
    }
}

在您的類中需要將GUI階段的場景更改為新場景,請調用:

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

使用靜態訪問器通常是可以的,因為您只能為給定的JVM執行啟動單個Application實例。 唯一真正的缺點是,在創建新場景的類和Application類之間存在編碼依賴關系。 但是,對於某些應用程序類型,這無關緊要。


靜態訪問器的另一種機制是動態獲取舞台,例如:

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