如果JavaFX中发生错误,如何从任何地方调用setOnCloseRequest来关闭应用程序?

如果JavaFX中发生错误,如何从任何地方调用setOnCloseRequest来关闭应用程序?,java,javafx-8,handler,Java,Javafx 8,Handler,在对话框中显示错误后,如何关闭JavaFX应用程序 大体上: primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent we) { logger.debug("Tool is closing..."); JDBCUtil.closeConnection(); // necessary

在对话框中显示错误后,如何关闭JavaFX应用程序

大体上:

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

    @Override
    public void handle(WindowEvent we) {
        logger.debug("Tool is closing...");
        JDBCUtil.closeConnection(); // necessary
    }
});
primaryStage.setOnCloseRequest(新的EventHandler(){
@凌驾
公共无效句柄(WindowEvent we){
调试(“工具正在关闭…”);
JDBCUtil.closeConnection();//必要
}
});
在另一类中:

// ... 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...
}
/。。。创建对话框、警报等。
可选结果=exception.showAndWait();
如果(result.get().getButtonData()==ButtonData.CANCEL\u CLOSE){
Platform.exit();//但是没有调用handle方法。。。
}
虽然将处理
setOnHiding()
事件,但当检测到应用程序级关闭时(
Platform.exit()
已被调用),将不会调用
setOnCloseRequest()

它没有连接到stage,因此即使在
对话框中添加
setOnCloseRequest()
,也不会调用它

这些阶段级方法(例如,
setOnCloseRequest
setOnCloseRequest
)不是检测和处理应用程序级关闭事件的正确方法。相反,您应该从应用程序实现,以检测应用程序关闭,并处理所需的操作

所以在您的主要应用程序中

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