[英]JavaFX: How to overwrite button action in custom Dialog
我在基于 JDK 8 和 JavaFX 的桌面应用程序上工作。
我用 2 个按钮(完成和取消)创建了自定义对话框 class。 我的目标是返回对话框中添加的字符串列表(单击完成按钮后,对话框返回列表。取消返回空列表)。
我有问题,因为 function showAndWait 返回我单击的按钮类型('ButtonType.FINISH' 或 'ButtonType.CANCEL')。 我的目标是覆盖完成和关闭按钮的默认操作,我想返回列表而不是返回按钮类型。
始终可以创建自定义按钮,但是,最好使用 JavaFX 已经提供的那些。
作为回应,您可以使用任何 JVM 语言 (Java/Kotlin/Scala)。
代码:
class MyDialog : Dialog<MutableList<String>>() {
val listToReturn: MutableList<String> = mutableListOf()
init {
val dialogPane: DialogPane = this.dialogPane
dialogPane.buttonTypes.addAll(ButtonType.FINISH, ButtonType.CANCEL)
}
}
val myDialog: MyDialog = MyDialog()
// here I got ButtonType ('ButtonType.FINISH' or 'ButtonType.CANCEL'), not list of string
myDialog.showAndWait().ifPresent { list -> println(list) }
您需要使用结果转换器
public class MyDialog extends Dialog<List<String>> {
ArrayList<String> returnList = new ArrayList<>();
public MyDialog() {
returnList.add("test 1");
returnList.add("test 2");
this.getDialogPane().getButtonTypes().addAll(ButtonType.FINISH, ButtonType.CANCEL);
setResultConverter(dialogButton -> {
if (dialogButton == ButtonType.FINISH) {
return returnList;
}
return new ArrayList<>();
});
}
}
对于应用程序方面
public class main extends Application {
public static void main (String [] args) {
launch();
}
@Override
public void start(Stage primaryStage) {
MyDialog myDialog = new MyDialog();
myDialog.showAndWait().ifPresent(System.out::println);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.