JavaFX stage.setOnCloseRequest without function?


Question

This is my Start-Methode. First i create a stage and set a title and a scene. And i wanna create a dialog if someone wants to close the window on the window-close-btn [X]. i thought i will catch this event with the setOnCloseRequest()-function. But i still can close all stages i open while runtime.

@Override
public void start(final Stage primaryStage) throws Exception {
    primaryStage.setTitle("NetControl");
    primaryStage.setScene(
            createScene(loadMainPane())
    );

    primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
        @Override
        public void handle(final WindowEvent event) {
            //Stage init
            final Stage dialog = new Stage();
            dialog.initModality(Modality.APPLICATION_MODAL);

            // Frage - Label
            Label label = new Label("Do you really want to quit?");

            // Antwort-Button JA
            Button okBtn = new Button("Yes");
            okBtn.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    dialog.close();
                }
            });

            // Antwort-Button NEIN
            Button cancelBtn = new Button("No");
            cancelBtn.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    primaryStage.show();
                    dialog.close();
                }
            });
        }
    });

    primaryStage.show();
}

private Pane loadMainPane() throws IOException {
    FXMLLoader loader = new FXMLLoader();

    Pane mainPane = (Pane) loader.load(
            getClass().getResourceAsStream(ContentManager.DEFAULT_SCREEN_FXML)
    );

    MainController mainController = loader.getController();

    ContentManager.setCurrentController(mainController);
    ContentManager.loadContent(ContentManager.START_SCREEN_FXML);

    return mainPane;
}

private Scene createScene(Pane mainPane) {
    Scene scene = new Scene(mainPane);
    setUserAgentStylesheet(STYLESHEET_MODENA);
    return scene;
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    Application.launch(args);
}

Are there any other functions to catch the window-events? or isnt it logical to run the CloseRequest on the primaryStage, i read something with platforms (but i dont know if it necessary for my problem)?

1
2
4/18/2014 7:06:00 PM

Accepted Answer

In the onCloseRequest handler, call event.consume();.

That will prevent the primary stage from closing.

Remove the primaryStage.show(); call from the cancel button's handler and add a call to primaryStage.hide(); in the OK button's handler.

9
4/18/2014 7:31:33 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon