JavaFX类控制器阶段/窗口引用

有没有办法从关联的类控制器获取FXML加载文件的Stage / Window对象?

特别是,我有一个模态窗口的控制器,我需要舞台来关闭它。

我找不到一个优雅的解决方案。 但我发现了这两种选择:

  • 从场景中的节点获取窗口引用

    @FXML private Button closeButton ; public void handleCloseButton() { Scene scene = closeButton.getScene(); if (scene != null) { Window window = scene.getWindow(); if (window != null) { window.hide(); } } } 
  • 加载FXML时,将Window作为参数传递给控制器​​。

     String resource = "/modalWindow.fxml"; URL location = getClass().getResource(resource); FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(location); fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory()); Parent root = (Parent) fxmlLoader.load(); controller = (FormController) fxmlLoader.getController(); dialogStage = new Stage(); controller.setStage(dialogStage); ... 

    而FormController必须实现setStage方法。

 @FXML private Button closeBtn; Stage currentStage = (Stage)closeBtn.getScene().getWindow(); currentStage.close(); 

另一种方法是为舞台和访问它定义静态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(); } }