【问题标题】:JavaFX Class controller Stage/Window referenceJavaFX 类控制器舞台/窗口参考
【发布时间】:2012-10-12 12:07:27
【问题描述】:

有什么方法可以从关联的类控制器中获取 FXML 加载文件的 Stage/Window 对象?

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

【问题讨论】:

    标签: java javafx-2 javafx


    【解决方案1】:

    我找不到该问题的优雅解决方案。但我找到了这两种选择:

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

      @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方法。

    【讨论】:

      【解决方案2】:
      @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();
      }
      }
      

      【讨论】:

        猜你喜欢
        • 2012-10-07
        • 2019-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多