javafx.scene.control.Dialog won't close on pressing “x”

前端 未结 5 1045
傲寒
傲寒 2020-12-06 17:36

If I just create an empty class extending from javafx.scene.control.Dialog, it won\'t close when I\'m pressing the \"x\" button in the top right corner

5条回答
  •  青春惊慌失措
    2020-12-06 18:13

    To work-around this, you could add a hidden close button to the dialog.

    import javafx.application.Application;
    import javafx.scene.*;
    import javafx.scene.control.*;
    import javafx.stage.Stage;
    
    public class DialogClosure extends Application{
    
        @Override
        public void start(Stage stage) throws Exception {
            Button openDialog = new Button("Open Dialog");
            openDialog.setOnAction(event -> {
                Dialog dialog = new Dialog();
                dialog.getDialogPane().getButtonTypes().add(ButtonType.CLOSE);
                Node closeButton = dialog.getDialogPane().lookupButton(ButtonType.CLOSE);
                closeButton.managedProperty().bind(closeButton.visibleProperty());
                closeButton.setVisible(false);
                dialog.showAndWait();
            });
    
            stage.setScene(new Scene(openDialog));
            stage.show();
        }
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    Then the dialog meets both your requirement of being able to be closed via the native windowing system's window close icon as well as the JavaFX Dialog requirement of including a close button in the dialog for the close icon to work.

    Alternately, you could use a Stage with showAndWait instead of a Dialog. A Stage without any included buttons is closable using the windowing system's close window icon.

提交回复
热议问题