3 Replies Latest reply: Nov 4, 2012 7:41 AM by J. Ishikawa RSS

    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?

      Particularly, I have a controller for a modal window and I need the Stage to close it.
        • 1. Re: Class controller Stage/Window reference
          You can retrieve a reference to the window to which any Node belongs with
          Window window = null ;
          Scene scene = myNode.getScene();
          if (scene!=null) {
            window = scene.getWindow();
          You need to do this in an event handler method in your controller, not in the initialize() method. At the time the initialize method is called, the object loaded by the FXML file will (likely) not have been added to a window. So the controller will look something like:
          @FXML private Button closeButton ;
          public void handleCloseButton() {
            Scene scene = closeButton.getScene();
            if (scene != null) {
              Window window = scene.getWindow();
              if (window != null) {
          • 2. Re: Class controller Stage/Window reference
            J. Ishikawa

            I have a parent FXML-file (no controller added) acting as main frame, which includes several other FXML-files. In one of those included FXML-files, I have added a controller.

            So, my setup looks a bit like this...
            -> Parent FXML
            --> include FXML-file1 + controller attached
            --> ...
            --> include FXML-file5

            Inside that controller, I am trying to access now the stage object in a similar approach like described here. This is when i get the null pointer exception....

            public class FXMLfile1Controller {

            private Button ButtonXYZ;

            protected void ButtonXYZ_Action(ActionEvent event) {
            Stage stage = (Stage)ButtonXYZ.getScene().getWindow();

            // this doesnt work either....
            // stage.close();

            Can it be, that the stage-object in the controller is not the same as the stage of the parent/main FXML?
            • 3. Re: Class controller Stage/Window reference
              J. Ishikawa
              I found the problem. I referenced the ID of the button and not the fx:id.