换句话说,Application.stop()是最后一次机会,虽然它确实阻止了退出,但撤销退出流程还有点晚.
原文链接:https://www.f2er.com/windows/364730.html更好的是为关闭请求设置一个监听器,可以通过使用该事件来取消该监听器.
在应用程序类中:
public void start(Stage stage) throws Exception { FXMLLoader ldr = new FXMLLoader(getClass() .getResource("Application.fxml")); Parent root = (Parent) ldr.load(); appCtrl = (ApplicationController) ldr.getController(); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); scene.getWindow().setOnCloseRequest(new EventHandler<WindowEvent>() { public void handle(WindowEvent ev) { if (!appCtrl.shutdown()) { ev.consume(); } } }); }
然后在应用程序控制器中,上面引用为appCtrl:
/** reference to the top-level pane */ @FXML private AnchorPane mainAppPane; public boolean shutdown() { if (model.isChanged()) { DialogResult userChoice = ConfirmDialog.showYesNoCancelDialog("Changes Detected","Do you want to save the changes? Cancel revokes the " + "exit request.",mainAppPane.getScene().getWindow()); if (userChoice == DialogResult.YES) { fileSave(null); if (model.isChanged()) { // cancelled out of the save,so return to the app return false; } } return userChoice == DialogResult.NO; } return true; }
注意:在FXML中引用mainAppPane(在这种情况下使用JavaFX Scene Builder)以允许访问场景和窗口;该对话框是从https://github.com/4ntoine/JavaFxDialog扩展而来的对象,fileSave是File – >的事件处理程序.保存菜单项.对于文件 – >退出菜单项:
@FXML private void fileExitAction(ActionEvent ev) { if (shutdown()) { Platform.exit(); } }
希望这有助于某人!