Reputation:
I want to modify the default exit procedure in my javafx application to display a confirmation dialogue to the user. The confirmation dialogue will exit the application if the user chooses OK and will keep the application running when user chooses Cancel.
What should I do to make this in javaFX?
Upvotes: 1
Views: 1088
Reputation: 11
I Followed this approach...
After creating my stage I use this code to launch a popup and exit...
stage.setOnCloseRequest((WindowEvent arg0) -> {
arg0.consume();
Alert exitAlert = new Alert(AlertType.CONFIRMATION);
exitAlert.setTitle("Exit Confirmation");
exitAlert.setHeaderText(null);
exitAlert.setContentText("Do you really need to exit ?");
ButtonType yesBtn = new ButtonType("Yes", ButtonData.YES);
ButtonType noBtn = new ButtonType("No", ButtonData.NO);
exitAlert.getButtonTypes().setAll(yesBtn, noBtn);
exitAlert.initOwner(getScene().getWindow());
exitAlert.showAndWait();
if (exitAlert.getResult().getButtonData() == ButtonData.YES) {
Platform.exit();
System.exit(0);
}
});
Upvotes: 1
Reputation: 10989
You can use Alert since 8.40
stage.setOnCloseRequest(evt -> {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Confirm Close");
alert.setHeaderText("Close program?");
alert.showAndWait().filter(r -> r != ButtonType.OK).ifPresent(r->evt.consume());
});
Upvotes: 2
Reputation: 927
primaryStage.addEventFilter(WindowEvent.WINDOW_CLOSE_REQUEST, e->{
e.consume();
Popup popup = new Popup();
HBox buttons = new HBox();
Button close = new Button("close");
Button cancel = new Button("cancel");
buttons.getChildren().addAll(close,cancel);
buttons.setPadding(new Insets(5,5,5,5));
popup.getContent().add(buttons);
popup.show(primaryStage);
close.setOnAction(ex -> {
Platform.exit();
});
cancel.setOnAction(ec -> {
popup.hide();
});
});
Upvotes: 1