简体   繁体   中英

Communicating between stages in JavaFx (using *.fxml)

I want to write simple application where when you click to close - the new window (stage) pushing up and ask you if you really want it. I know how it realize programmatically but don't know how it realize using fxml and controllers .

If for main application stage and confirm stage will be using separated controllers and each controller will be mapped for one fxml file only how can I return result value from confirm to main stage?

I think you might need simple Dialog or Alert . If you don't like how default Java Dialogs look, you can extend DialogPane (or Dialog itself), design it in FXML and setDialogPane to your Dialog.

Here is how to create, show and get result from simple Alert without any fancy looks:

Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.showAndWait().ifPresent(response -> {
 if (response == ButtonType.OK) {
     System.out.println("User clicked OK");
 }
});

To the part of closing the main Stage. You can intercept and handle close requests.

stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
        @Override
        public void handle(WindowEvent event) {
            System.out.println("I will not close");
            event.consume();
        }
    });

By consuming the event, you can prevent stage from closing if you want.

So if you want confirmation from user, just put Alert into onCloseRequest handling and consume the event if he makes up his mind (clicks to cancel).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM