So I have 2 stages, one is the main stage and the other is a pop-up screen. When the pop-up screen shows up you can close it by pressing the 'x' at the upper-left (or upper-right depending on your OS). Is there a way to close the main stage whenever you close the pop-up screen?
Asked
Active
Viewed 672 times
1
-
1Call `Platform.exit()` in the close hook (`popup.setOnCloseRequest(...)`). – Ironcache May 02 '16 at 20:07
-
`onCloseRequest` is not really the correct event here: that is called when the user clicks on the close button for the popup. It can be vetoed at that point, so the popup might not really close. You should use `onHidden()`. – James_D May 02 '16 at 22:40
2 Answers
2
Stage
and Popup
inherit an onHidden
property from Window
. This is a handler that is invoked immediately after the window is hidden (by any mechanism). You can call Platform.exit()
in the handler in order to exit the application:
popup.setOnHidden(event -> Platform.exit());
Note that Platform.exit()
is generally preferred to System.exit(0)
: calling System.exit(...)
will not allow the Application
's stop()
method to be called, so you may bypass any resource clean-up your application is performing.

James_D
- 201,275
- 16
- 291
- 322
-
Which one is better to use between `Platform.exit()` and `System.exit(...)` in general cases? I have read some Stackoverflow questions and found that [some people](http://stackoverflow.com/questions/14938279/javafx-application-still-running-after-close) are using both. And some of them are not interested using it as sometime it may not work. – Rana Depto May 03 '16 at 04:51
-
1
There have a Event named setOnCloseRequest
. If you are opening an Alert
pop-up window.
Alert popup = new Alert(AlertType.INFORMATION);
Then your solution is:
alert.setOnCloseRequest(new EventHandler<DialogEvent>()
{
@Override
public void handle(DialogEvent t)
{
System.exit(0);
}
});
Else if you want to close another window with it's owner, then just use it's stage
and replace DialogEvent
with WindowEvent
.

Rana Depto
- 721
- 3
- 11
- 31
-
1`onCloseRequest` is not the correct event to use here: it only gets invoked if there is an "external" request to close the window; usually this means the user presses the native window close button. It is possible to veto the request, in which case the `onCloseRequest` handler gets invoked even though the window does not close. – James_D May 02 '16 at 22:45