JavaFX类控制器Stage/Window引用

5

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

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

2个回答

8

我找不到一个优雅的解决方案,但我找到了这两个替代方案:

  • Getting the window reference from a Node in the Scene

    @FXML private Button closeButton ;
    
    public void handleCloseButton() {
      Scene scene = closeButton.getScene();
      if (scene != null) {
        Window window = scene.getWindow();
        if (window != null) {
          window.hide();
        }
      }
    }
    
  • Passing the Window as an argument to the controller when the FXML is loaded.

    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);
    
    ...
    

    And FormController must implement the setStage method.


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

另一种方法是定义一个静态 getter 来访问 Stage。

主类

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接