cy221
cy221

Reputation: 1147

How to call setOnCloseRequest from anywhere to close application if an error occurs in JavaFX?

How can I close my JavaFX application after showing the error in a dialog?

In main:

primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {

    @Override
    public void handle(WindowEvent we) {
        logger.debug("Tool is closing...");
        JDBCUtil.closeConnection(); // necessary
    }
});

In another class :

// ... creating Dialog, Alert, etc. 
Optional<ButtonType> result = exception.showAndWait();
if (result.get().getButtonData() == ButtonData.CANCEL_CLOSE) {
    Platform.exit(); // but the handle method isn't called then...
}

Upvotes: 3

Views: 2137

Answers (1)

vtor
vtor

Reputation: 9329

Although setOnHiding() event will be handled, setOnCloseRequest() will not be called when application level shutdown has been detected (Platform.exit() has been called).

This is not connected to the stage, so even if you add setOnCloseRequest() in your dialog stage, it wouldn't be called.

Those kind of stage level methods (e.g. setOnCloseRequest, setOnCloseRequest) are not the correct methods to detect and process application level shutdown event. Instead, you should implement stop() from Application, to detect application shutdown, and handle needed actions.

So in your primary application,

@Override
public void stop() throws Exception {
     JDBCUtil.closeConnection(); 
     super.stop();
}

Upvotes: 2

Related Questions