JavaFX - how to know if cancel was pressed

ALSTRA picture ALSTRA · Jul 28, 2015 · Viewed 8k times · Source

How can I know if the OK or the Cancel Button was pressed in this JavaFX dialog.

The Dialog Code:

public String delimiter;

public void delimiterYES() throws IOException {
    delimiter=new String();
    TextInputDialog dialog = new TextInputDialog();
    dialog.setTitle("Delimiter");
    dialog.setHeaderText("Enter the delimiter");

    Optional<String> result = dialog.showAndWait();
    if (result.isPresent()) {
        delimiter=result.get();
    }
}

Answer

jewelsea picture jewelsea · Jul 28, 2015

If a result is present, then the user pressed OK. If no result is present, then the user probably pressed cancel, but they might have just closed the dialog window using the OS close window function.

Optional<String> result = new TextInputDialog().showAndWait();
if (result.isPresent()) {
    // ok was pressed.
} else {
    // cancel might have been pressed.
}

To really know if a button was pressed, you can use a filter as noted in the Dialog javadoc section "Dialog Validation / Intercepting Button Actions".

final Button cancel = (Button) dialog.getDialogPane().lookupButton(ButtonType.CANCEL);
cancel.addEventFilter(ActionEvent.ACTION, event ->
    System.out.println("Cancel was definitely pressed")
);

Sample code:

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;

import java.util.Optional;

public class DialogSample extends Application {
    @Override
    public void start(Stage stage) throws Exception {
        Button showButton = new Button("show");
        showButton.setOnAction(event -> showDialog(stage));
        showButton.setPrefWidth(100);
        stage.setScene(new Scene(showButton));
        stage.show();

        showButton.fire();
    }

    private void showDialog(Stage stage) {
        TextInputDialog dialog = new TextInputDialog();
        dialog.initOwner(stage);
        dialog.setTitle("Delimiter");
        dialog.setHeaderText("Enter the delimiter");

        final Button ok = (Button) dialog.getDialogPane().lookupButton(ButtonType.OK);
        ok.addEventFilter(ActionEvent.ACTION, event ->
            System.out.println("OK was definitely pressed")
        );

        final Button cancel = (Button) dialog.getDialogPane().lookupButton(ButtonType.CANCEL);
        cancel.addEventFilter(ActionEvent.ACTION, event ->
            System.out.println("Cancel was definitely pressed")
        );

        Optional<String> result = dialog.showAndWait();
        if (result.isPresent()) {
            System.out.println("Result present => OK was pressed");
            System.out.println("Result: " + result.get());
        } else {
            System.out.println("Result not present => Cancel might have been pressed");
        }    
    }

    public static void main(String[] args) {
        Application.launch();
    }
}