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

thi*_*ult 13 java javafx javafx-8

从jdk 8u40开始,我正在使用新的javafx.scene.control.AlertAPI来显示确认对话框.在下面的示例中,默认情况下"是"按钮而不是"否"按钮:

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

我不知道如何改变它.

编辑:

这里是默认情况下聚焦"是"按钮的结果屏幕截图:

在此输入图像描述

cru*_*sam 16

我不确定以下是否通常这样做,但你可以通过查找按钮并自己设置默认行为来更改默认按钮:

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


She*_*epy 6

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

用法:

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


Jos*_*eda 5

如果您查看(私有)ButtonBarSkin类,会发现有一个名为的方法,该方法doButtonOrderLayout()基于某些默认操作系统行为来执行按钮的布局。

在里面,你可以读到这样的内容:

/* 现在所有按钮都已放置,我们需要确保焦点设置在正确的按钮上。[...] 如果是这样,我们请求将焦点放在这个默认按钮上。*/

由于ButtonType.YES是默认按钮,因此它将成为焦点按钮。

所以@ymene 的答案是正确的:您可以更改默认行为,然后重点关注的将是NO.

或者您可以通过BUTTON_ORDER_NONEbuttonOrderProperty(). 现在第一个按钮将获得焦点,因此您需要先放置该NO按钮。

alert.getButtonTypes().setAll(ButtonType.NO, ButtonType.YES);

ButtonBar buttonBar=(ButtonBar)alert.getDialogPane().lookup(".button-bar");
buttonBar.setButtonOrder(ButtonBar.BUTTON_ORDER_NONE);
Run Code Online (Sandbox Code Playgroud)

请注意,YES仍将具有默认行为:这意味着NO可以使用空格键(焦点按钮)进行选择,而YES如果按 Enter 键(默认按钮)则将选择。

警报对话框

或者您也可以更改@crusam 答案后的默认行为。