【发布时间】:2020-02-06 19:27:37
【问题描述】:
我想创建一个自定义 Dialog,它只显示选项(见图 1)。如果用户选择其中一个选项,对话框应该立即关闭并返回相应的结果。
到目前为止,我只能通过将任意ButtonType 添加到Dialog、使用setVisible(false) 隐藏它并在单击选项的EventHandler 中应用fire() 来实现此目的。
这种奇怪的解决方法实际上效果很好,但在我看来非常不专业......
那么,在不使用 ButtonType 技巧的情况下,如何以更专业或更恰当的方式进行操作?
我的解决方法代码如下所示(Dialog 类):
public class CustomDialog extends Dialog<String> {
private static final String[] OPTIONS
= new String[]{"Option1", "Option2", "Option3", "Option4"};
private String selectedOption = null;
Button applyButton;
public CustomDialog() {
super();
initStyle(StageStyle.DECORATED);
VBox vBox = new VBox();
for (String option : OPTIONS) {
Button optionButton = new Button(option);
optionButton.setOnAction((event) -> {
selectedOption = option;
applyButton.fire();
});
vBox.getChildren().add(optionButton);
}
getDialogPane().setContent(vBox);
getDialogPane().getButtonTypes().add(ButtonType.APPLY);
applyButton = (Button) getDialogPane().lookupButton(ButtonType.APPLY);
applyButton.setVisible(false);
setResultConverter((dialogButton) -> {
return selectedOption;
});
}
}
使用对话框类:
CustomDialog dialog = new CustomDialog();
Optional<String> result = dialog.showAndWait();
String selected = null;
if (result.isPresent()) {
selected = result.get();
} else if (selected == null) {
System.exit(0);
}
【问题讨论】:
-
你需要去docs.oracle.com/javase/8/javafx/api/javafx/scene/control/…。阅读标记为
Dialog Closing Rules的部分 -
抱歉,您没有阅读我的代码和问题吗?我的问题是如何在不需要使用任何 ButtonType 控件的情况下使用对话框?通用规则说这是不可能的,所以我的解决方法似乎是我问题的唯一解决方案,你所做的就是引用某事。我们都已经很清楚了 ;-) ...
-
A
Dialog是DialogPane的重量级容器,如文档中所述,“DialogPane在ButtonType的概念上运行。”因此,如果您不想要任何ButtonType功能,似乎Dialog不是要使用的正确类。也许您的问题中没有说明您想要的其他一些功能,但普通的Stage不会在这里做您需要的事情吗? -
所以你问了一个你知道做不到的问题?