5

I have a Stage in JavaFX that can be closed in multiple ways, either by clicking the red (X) or by a Button which calls stage.close()

Regardless of how the Stage is closed, I would like to perform an action before (or as) it is closed.

If I use the following code:

myStage.setOnCloseRequest( event -> {System.out.println("Closing Stage");} );

then the handler is called when I click the (X) but not when I call myStage.close()

This is the same issue that this question talks about (with a key difference): JavaFX: Stage close handler

The difference is that he wants to call a handler as the entire application is closed, and therefore can override the Application's stop() method. However I'm not closing the entire application, just one stage. And Stage does not have a stop() method to override.

Thanks for any help.

skrilmps
  • 625
  • 2
  • 10
  • 29
  • 5
    You can use [setOnHiding](http://docs.oracle.com/javase/8/javafx/api/javafx/stage/Window.html#setOnHiding-javafx.event.EventHandler-) if you don’t intend to prevent the Stage from closing. – VGR Jun 14 '17 at 15:11
  • @VGR Thanks. So a Stage is also hidden as it is closed? And, would this event also be invoked every time the window is concealed or minimized? – skrilmps Jun 14 '17 at 15:13
  • 1
    From the [Stage documentation](http://docs.oracle.com/javase/8/javafx/api/javafx/stage/Stage.html): “Use the showAndWait() method if you need to block the caller until the modal stage is hidden (closed).” ‘Hidden’ and ‘closed’ are synonyms, when it comes to JavaFX Stages and Windows. – VGR Jun 14 '17 at 15:19
  • @VGR Great, thanks! – skrilmps Jun 14 '17 at 15:20

1 Answers1

10

Thanks to comments by VGR, the solution I was looking for really was as simple as replacing setOnCloseRequest with setOnHiding:

myStage.setOnHiding( event -> {System.out.println("Closing Stage");} );
skrilmps
  • 625
  • 2
  • 10
  • 29