从 jdk 8u40 开始,我使用新的 javafx.scene.control.Alert
API 来显示确认对话框。在下面的示例中,"is"按钮默认获得焦点,而不是“否”按钮:
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;
}
我不知道如何改变它。
编辑:
这里是"is"按钮默认聚焦的结果截图:
最佳答案
我不确定以下是否是通常执行此操作的方式,但您可以通过查找按钮并自行设置默认行为来更改默认按钮:
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;
}
关于警告对话框中的 JavaFX 默认聚焦按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29535395/