Search code examples
javafxoption-type

Optional for showAndWait


My question is when the showAndWait's output is null? Because in my program it has two ok and cancel buttons and neither of the cancel and close buttons gives null output.

 dialog.showAndWait().ifPresent(buttonType -> {
        System.out.println(buttonType);
}

when I press the close button(X) and the cancel button the output is(not null):

ButtonType [text=Cancel, buttonData=CANCEL_CLOSE]

Solution

  • Note that Dialog#showAndWait() returns an Optional and will never return null. However, the returned Optional may be empty. From reading through the documentation, this will occur in the following cases:

    • The result converter returns null.
    • There is only one non-cancel button and the dialog is closed "abnormally" (e.g. the X button is clicked).
      • But note this will give you an empty Optional only if the result converter returns null (or there's no result converter) and the result property contains null.

    Here's an example:

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.ButtonType;
    import javafx.scene.control.Dialog;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;
    
    public class App extends Application {
    
      @Override
      public void start(Stage primaryStage) {
        var btn = new Button("Show dialog...");
        btn.setOnAction(
            e -> {
              Dialog<Object> dialog = new Dialog<>();
              dialog.setContentText("Empty Optional test.");
              dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
              dialog
                  .showAndWait()
                  .ifPresentOrElse(System.out::println, () -> System.out.println("NO RESULT"));
            });
        var scene = new Scene(new StackPane(btn), 600, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
      }
    }
    

    Running the above, showing the dialog, and then clicking the X button will result in the following output:

    NO RESULT
    

    In other words, the Optional was empty.


    You mention your tests include cancel buttons. That's why you see a non-empty Optional, because by default the result will be the first matching cancel button when the dialog is closed "abnormally". See the "Dialog Closing Rules" section of Dialog's Javadoc for more information.