简体   繁体   English

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

[英]JavaFX Class controller Stage/Window reference

Is there any way of getting the Stage/Window object of an FXML loaded file from the associated class controller? 有没有办法从关联的类控制器获取FXML加载文件的Stage / Window对象?

Particularly, I have a controller for a modal window and I need the Stage to close it. 特别是,我有一个模态窗口的控制器,我需要舞台来关闭它。

I could not find an elegant solution to the problem. 我无法找到解决问题的优雅方案。 But I found these two alternatives: 但我发现了这两种选择:

  • 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. 加载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); ... 

    And FormController must implement the setStage method. 而FormController必须实现setStage方法。

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

Another way is define a static getter for the Stage and Access it 另一种方法是为舞台和访问它定义静态getter

Main Class 主类

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

Now you Can access this stage by calling 现在您可以通过调用访问此阶段

Main.getPrimaryStage() Main.getPrimaryStage()

In Controller Class 在控制器类中

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