【问题标题】:Is it possible to use a specific class in the javafx Dialog?是否可以在 javafx 对话框中使用特定的类?
【发布时间】:2017-04-06 13:07:50
【问题描述】:

我正在寻找 javafx JOptionPane 等价物,我确实找到了一个很棒的类 Dialog。所以在教程中,导师使用:Dialog<Pair<String,String>> 来获取两个字符串输入字段,从这里我想知道是否可以使用一个类让我们说:Dialog<Product>。如果可能的话,我应该如何写这门课是他们的任何特定模式或情节吗? 谢谢

【问题讨论】:

  • 这个想法闪过我的脑海,因为我已经在 J​​AVAFX 和 JPA 之间使用适配器模式

标签: java javafx dialog


【解决方案1】:

是的,你可以这样做。我的回答基于:

https://examples.javacodegeeks.com/desktop-java/javafx/dialog-javafx/javafx-dialog-example/

假设您的产品有两个可以通过构造函数传递的字段:

String name;
float price;

你可以这样创建你的对话框:

Dialog<Product> dialog = new Dialog<>();
dialog.setTitle("Product Dialog");
dialog.setResizable(true);

Label nameLabel = new Label("Name: ");
Label priceLabel = new Label("Price: ");
TextField nameField = new TextField();
TextField priceField = new TextField();

GridPane grid = new GridPane();
grid.add(nameLabel, 1, 1);
grid.add(nameField, 2, 1);
grid.add(priceLabel, 1, 2);
grid.add(priceField, 2, 2);
dialog.getDialogPane().setContent(grid);

ButtonType saveButton = new ButtonType("Save", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().add(saveButton);

dialog.setResultConverter(new Callback<ButtonType, Product>() {
    @Override
    public Product call(ButtonType button) {
        if (button == saveButton) {
            String name = nameField.getText();
            Float price;
            try {
                price = Float.parseFloat(priceField.getText());
            } catch (NumberFormatException e) {
                // Add some log or inform user about wrong price
                return null;
            }

            return new Product(name, price);
        }

        return null;
    }
});

Optional<Product> result = dialog.showAndWait();

if (result.isPresent()) {
    Product product = result.get();
    // Do something with product
}

【讨论】:

  • 不鼓励仅链接的答案,因为如果外部 URL 消失,您的答案对未来的读者毫无用处。请为您的答案添加解释。
  • 谢谢,我会尽量把这个答案封装起来,以备将来使用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-22
  • 2016-02-09
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多