“警报”对话框中的 JavaFX 默认焦点按钮

2022-09-03 17:51:33

从jdk 8u40开始,我使用新的API来显示确认对话框。在下面的示例中,默认情况下,“是”按钮是焦点,而不是“否”按钮:javafx.scene.control.Alert

public boolean showConfirmDialog(String title, String header, String content, AlertType alertType) {
    final Alert alert = new Alert(alertType);
    alert.setTitle(title);
    alert.setHeaderText(header);
    alert.setContentText(content);

    alert.getButtonTypes().clear();
    alert.getButtonTypes().addAll(ButtonType.YES, ButtonType.NO);

    final Optional<ButtonType> result = alert.showAndWait();
    return result.get() == ButtonType.YES;
}

我不知道如何改变它。

编辑:

以下是默认情况下“是”按钮聚焦的结果的屏幕截图:

enter image description here


答案 1

我不确定以下是否是通常执行此操作的方法,但是您可以通过查找按钮并自己设置默认行为来更改默认按钮:

public boolean showConfirmDialog(String title, String header, String content, AlertType alertType) {
    final Alert alert = new Alert(alertType);
    alert.setTitle(title);
    alert.setHeaderText(header);
    alert.setContentText(content);

    alert.getButtonTypes().clear();
    alert.getButtonTypes().addAll(ButtonType.YES, ButtonType.NO);

    //Deactivate Defaultbehavior for yes-Button:
    Button yesButton = (Button) alert.getDialogPane().lookupButton( ButtonType.YES );
    yesButton.setDefaultButton( false );

    //Activate Defaultbehavior for no-Button:
    Button noButton = (Button) alert.getDialogPane().lookupButton( ButtonType.NO );
    noButton.setDefaultButton( true );

    final Optional<ButtonType> result = alert.showAndWait();
    return result.get() == ButtonType.YES;
}

答案 2

一个简单的功能,多亏了crusam:

private static Alert setDefaultButton ( Alert alert, ButtonType defBtn ) {
   DialogPane pane = alert.getDialogPane();
   for ( ButtonType t : alert.getButtonTypes() )
      ( (Button) pane.lookupButton(t) ).setDefaultButton( t == defBtn );
   return alert;
}

用法:

final Alert alert = new Alert( 
         AlertType.CONFIRMATION, "You sure?", ButtonType.YES, ButtonType.NO );
if ( setDefaultButton( alert, ButtonType.NO ).showAndWait()
         .orElse( ButtonType.NO ) == ButtonType.YES ) {
   // User selected the non-default yes button
}

推荐