java - 是否可以在 javafx 对话框中使用特定的类?

标签 java javafx dialog

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

最佳答案

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

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
}

关于java - 是否可以在 javafx 对话框中使用特定的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43256161/

相关文章:

java - 用 Java 解析 XML

JavaFX 显示可缩放 vector 图形?

user-interface - 如何将choose.file() 对话框置于前台

jsf - 素面 : update dialog content and keep it open

java - 检测 Java 中的 Dll

java - 如何在tomcat servlet中限制上传文件的大小

java - 首次调用 stub 方法后,Mockito stub 消失

javafx - 传递参数JavaFX FXML

java - 如何使用另一个组合框中的选择来填充组合框? JavaFX

java - 对话框内容不根据该行变化