【问题标题】:JavaFX: How to overwrite button action in custom DialogJavaFX:如何覆盖自定义对话框中的按钮操作
【发布时间】:2020-07-26 07:06:12
【问题描述】:

我从事基于 JDK 8 和 JavaFX 的桌面应用程序。

我创建了带有 2 个按钮(完成和取消)的自定义对话框类。我的目标是返回对话框中添加的字符串列表(单击完成按钮后,对话框返回列表。取消返回空列表)。

我有问题,因为函数 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) }

【问题讨论】:

  • minimal reproducible example 请 .. 为了最好的机会吸引兴趣,我建议使用普通 javafx :)
  • @kleopatra 我添加的内容还不够吗?我专注于问题的本质,我想保持简洁。我可以在这段代码中添加的只是启动 javafx 应用程序并创建场景。
  • 也许我误解了这个问题,但是如果对象类型是MyDialog而不是Dialog,为什么不添加另一个函数呢? getList() 之类的东西在自身上运行 showAndWait 然后返回 listToReturn/Null。
  • 这是一个选项。但是,我更愿意以某种方式覆盖取消和完成按钮。

标签: java kotlin javafx


【解决方案1】:

您需要使用结果转换器

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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多