JavaFX class controller Stage / window reference

Is there a way to get the Stage / Window object of a loaded FXML file from a linked class controller?

In particular, I have a controller for the modal window, and I need a scene to close it.

+4
source share
2 answers

I could not find an elegant solution to the problem. But I found these two alternatives:

  • Getting a link to a window from Node in a 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 loading FXML.

     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.

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

Another way is to define a static getter for Stage and Access it

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

In the controller class

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

Source: https://habr.com/ru/post/1441330/


All Articles