JavaFX - 如何知道是否按下了取消

ALS*_*TRA 5 java dialog javafx cancel-button

如何在此JavaFX对话框中知道是否按下了"确定"或"取消"按钮.

对话代码:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

jew*_*sea 7

如果存在结果,则用户按下OK.如果没有结果,则用户可能按下取消,但他们可能刚刚使用OS关闭窗口功能关闭了对话窗口.

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

要确切地知道是否按下了按钮,可以使用Dialog javadoc "对话框验证/拦截按钮操作"部分中所述的过滤器.

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

示例代码:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)