如何将方法设置为 JavaFX 警报按钮

How to set a method to a JavaFX Alert Button

我想为按钮 "OK" 和 "Cancel" 提供一个方法,当用户单击这些按钮之一时将执行该方法:

如何使用我的代码执行此操作?

Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Test");
alert.setHeaderText("This is a test.");
alert.setResizable(false);
alert.setContentText("Select okay or cancel this alert.");
alert.showAndWait();

在我看来,为其中一个按钮设置动作的代码如下所示:

alert.setActionForButtonOK(OkMethod());

无需向按钮注册事件处理程序(顺便说一下,Dialog class 并非旨在提供对其按钮的直接访问)。您可以简单地检查 showAndWait 返回的值以获取用户按下的按钮并执行相应操作:

Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Test");
alert.setHeaderText("This is a test.");
alert.setResizable(false);
alert.setContentText("Select okay or cancel this alert.");

Optional<ButtonType> result = alert.showAndWait();
ButtonType button = result.orElse(ButtonType.CANCEL);

if (button == ButtonType.OK) {
    System.out.println("Ok pressed");
} else {
    System.out.println("canceled");
}

alert#showAndWait returns 一个 Optional 包含已按下的按钮(或 null 如果没有按下任何按钮并退出对话框)。使用该结果来选择您想要的操作 运行。例如

Optional<ButtonType> result = alert.showAndWait();
if(!result.isPresent())
    // alert is exited, no button has been pressed.
else if(result.get() == ButtonType.OK)
     //oke button is pressed
else if(result.get() == ButtonType.CANCEL)
    // cancel button is pressed

如上所述,对话框通常只收集输入,代码根据查看对话框 return 值是什么对该输入执行操作。 通常。然而,有很多例外原因。例如,自定义对话框可能需要在允许关闭之前验证输入字段,或者按钮可能用于调用控制操作等...

在您的对话框 class 中,您可以这样做:

final Button btnFoo = (Button) dialog.getDialogPane().lookupButton( buttonTypeFoo );

那么只需添加一个事件处理程序挂钩即可。如果您出于任何原因不想点击关闭对话框,请记住使用该事件:

btnFoo.setOnAction( event -> {
      onBtnFooClicked();
      event.consume();
    } );