需求是弹出一个等待弹框,禁止手动关闭,由后台线程执行完成后关闭。但发现如果不添加CLOSE或CANCEL按钮
即以下语句:
dialog.getDialogPane().getButtonTypes().add(ButtonType.CLOSE);
调用 dialog.close();是无效的。
查看源码
public final void close() {
if (isClosing) return;
isClosing = true;
final R result = getResult();
// if the result is null and we do not have permission to close the
// dialog, then we cancel the close request before any events are
// even fired
if (result == null && ! dialog.requestPermissionToClose(this)) {
isClosing = false;
return;
}
....
}
断点到此处便return了,也就是result为null,而且requestPermissionToClose返回true。
继续查看requestPermissionToClose
public boolean requestPermissionToClose(final Dialog<?> dialog) {
// We only allow the dialog to be closed abnormally (i.e. via the X button)
// when there is a cancel button in the dialog, or when there is only
// one button in the dialog. In all other cases, we disable the ability
// (as best we can) to close a dialog abnormally.
boolean denyClose = true;
// if we are here, the close was abnormal, so we must call close to
// clean up, if we don't consume the event to cancel closing...
DialogPane dialogPane = dialog.getDialogPane();
if (dialogPane != null) {
List<ButtonType> buttons = dialogPane.getButtonTypes();
if (buttons.size() == 1) {
denyClose = false;
} else {
// look for cancel button type
for (ButtonType button : buttons) {
if (button == null) continue;
ButtonBar.ButtonData type = button.getButtonData();
if (type == null) continue;
// refer to the comments in close() - we support both CANCEL_CLOSE
// and isCancelButton() for allowing a dialog to close in
// abnormal circumstances. This allows for consistency with
// the ESC key being pressed (which triggers the cancel button
// being pressed)
if (type == ButtonBar.ButtonData.CANCEL_CLOSE || type.isCancelButton()) {
denyClose = false;
break;
}
}
}
}
return !denyClose;
}
此处无法必须添加按钮,但需求是不能添加确认或取消按钮。只能通过设置result不为null,让程序继续往下走。
可以设置
dialog.setResult("1");
最终代码
javafx.scene.control.Dialog dialog = new javafx.scene.control.Dialog();
dialog.setTitle("提示");
dialog.setResult("1");
GridPane gridPane = new GridPane();
gridPane.setPrefWidth(200);
gridPane.setHgap(10);
gridPane.setVgap(10);
gridPane.setAlignment(Pos.CENTER);
gridPane.setPadding(new Insets(10, 10, 10, 10));
dialog.getDialogPane().setContent(gridPane);
ProgressIndicator indicator = new ProgressIndicator();
indicator.setPrefSize(30, 30);
gridPane.add(indicator, 0, 0);
gridPane.add(new Label(message), 0, 1);
dialog.show();
dialog.close();