title: JavaFX: Stage close handler
body: <p>I want to save a file before closing my JavaFX application.</p>
  
  <p>This is how I'm setting up the handler in <code>Main::start</code>:</p>
  
  <pre><code>primaryStage.setOnCloseRequest(event -&gt; {
      System.out.println("Stage is closing");
      // Save file
  });
  </code></pre>
  
  <p>And the controller calling <code>Stage::close</code> when a button is pressed:</p>
  
  <pre><code>@FXML
  public void exitApplication(ActionEvent event) {
      ((Stage)rootPane.getScene().getWindow()).close();
  }
  </code></pre>
  
  <p>If I close the window clicking the red X on the window border (the normal way) then I get the output message "<code>Stage is closing</code>", which is the desired behavior.</p>
  
  <p>However, when calling <code>Controller::exitApplication</code> the application closes without invoking the handler (there's no output).</p>
  
  <p>How can I make the controller use the handler I've added to <code>primaryStage</code>?</p>