簡體   English   中英

如何從Controller訪問JavaFx Stage?

[英]How to access a JavaFx Stage from a Controller?

我正在轉換一個純JavaFx應用程序,其中下面的代碼在將所有內容放在一個類中時工作正常,到FXML,其中Stage聲明和按鈕處理程序在不同的類中。 在一個Controller中,我試圖實現一個方法,允許用戶選擇一個目錄並將其存儲在一個變量中供以后使用:

private File sourceFile;
DirectoryChooser sourceDirectoryChooser;

@FXML
private void handleSourceBrowse() {
        sourceDirectoryChooser.setTitle("Choose the source folder");
        sourceFile = sourceDirectoryChooser.showDialog(theStage);
}

但是,“theStage”是該方法所需的階段,只在FolderSyncer4.java中存在(如果這是正確的術語):

public class FolderSyncer4 extends Application {

    final String FOLDER_SYNCER = "FolderSyncer";

    Stage theStage;

    @Override
    public void start(Stage primaryStage) throws Exception {
        theStage = primaryStage;

        //TODO do the FXML stuff, hope this works
        Parent root = FXMLLoader.load(getClass().getResource("FolderSyncerMainWindow.fxml"));
        theStage.setScene(new Scene(root, 685, 550));
        theStage.setTitle(FOLDER_SYNCER);
        theStage.show();
    }
}

我怎么繞過這個? 我需要以某種方式再次實現該方法,但突然間我不能將該階段作為參數傳遞。

在您的情況下,從處理程序的ActionEvent參數獲取場景可能最簡單:

@FXML
private void handleSourceBrowse(ActionEvent ae) {
    Node source = (Node) ae.getSource();
    Window theStage = source.getScene().getWindow();

    sourceDirectoryChooser.showDialog(theStage);
}

請參閱JavaFX:如何在初始化期間從控制器獲取階段? 了解更多信息。 我並不贊成最高級別的答案,因為它在加載了.fxml文件之后向控制器添加了編譯時依賴性(在所有問題都用javafx-2標記之后,所以不確定上述方法是否已經在那里工作,問題的背景看起來有點不同)。

另請參閱如何從控制器類中打開JavaFX FileChooser?

另一種方法是為舞台和訪問它定義靜態getter

主類

public class Main extends Application {
    private static Stage primaryStage; // **Declare static Stage**

    private void setPrimaryStage(Stage stage) {
        Main.primaryStage = stage;
    }

    static public Stage getPrimaryStage() {
        return Main.primaryStage;
    }

    @Override
    public void start(Stage primaryStage) throws Exception{
        setPrimaryStage(primaryStage); // **Set the Stage**
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }
}

現在您可以通過調用訪問此階段

Main.getPrimaryStage()

在控制器類中

public class Controller {
public void onMouseClickAction(ActionEvent e) {
    Stage s = Main.getPrimaryStage();
    s.close();
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM