我目前正在使用JavaFX创建一个对话框。 Dialog它自己运行得很好,但现在我正在尝试添加一个输入验证,当用户忘记填写文本字段时会警告用户。 我的问题就出现了:是否可以阻止对话框在Result Converter中关闭?像这样:
ButtonType buttonTypeOk = new ButtonType("Okay", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().add(buttonTypeOk);
dialog.setResultConverter((ButtonType param) -> {
if (valid()) {
return ...
} else {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setHeaderText("Pleas fill all fields!");
alert.showAndWait();
//prevent dialog from closing
}
});
我注意到如果在resault转换器中抛出错误,对话框不会关闭,但这似乎不是解决此问题的好方法。
如果无法以这种方式解决问题,我可以按this post中所述禁用按钮。但我希望保持按钮启用并显示一条消息。
提前谢谢!
答案 0 :(得分:18)
我在Javadoc中实际解释了如何在对话框中管理数据验证,我引用:
对话框验证/拦截按钮操作
在某些情况下,最好阻止对话框关闭 直到对话框的某些方面变得内部一致(例如a 对话框内的表单使所有字段都处于有效状态)。去做这个, 对话框API的用户应该熟悉
DialogPane.lookupButton(ButtonType)
方法。传入ButtonType
(已经在按钮类型列表中设置),用户将是 返回一个通常是Button类型的Node(但这取决于 如果DialogPane.createButton(ButtonType)
方法已经存在 覆盖)。使用此按钮,用户可以添加一个事件过滤器 在按钮执行其通常的事件处理之前调用,并且因此 用户可以通过使用该事件来阻止事件处理。这是一个 简化示例:
final Button btOk = (Button) dlg.getDialogPane().lookupButton(ButtonType.OK);
btOk.addEventFilter(
ActionEvent.ACTION,
event -> {
// Check whether some conditions are fulfilled
if (!validateAndStore()) {
// The conditions are not fulfilled so we consume the event
// to prevent the dialog to close
event.consume();
}
}
);
换句话说,您应该在按钮中添加一个事件过滤器,以便在未满足要求时使用该事件,这将阻止关闭对话框。
更多详情here
答案 1 :(得分:0)
解决此问题的另一种方法是使用setOnCloseRequest
,如果您不想仅在用户单击“确定”按钮时进行中继。当有外部请求关闭Dialog
时,将调用事件处理程序。然后事件处理程序可以通过消耗接收到的事件来防止对话框关闭。
setOnCloseRequest(e ->{
if(!valid()) {
e.consume();
}
});