是否可以在javafx对话框中使用特定的类?
问题描述:
我正在寻找javafx JOptionPane等价物,并且我找到了一个很棒的类Dialog。所以在本教程中,导师使用:Dialog<Pair<String,String>>
来获得两个字符串输入字段,从这里我想知道是否可以使用类说:Dialog<Product>
。如果可能的话,我应该如何写这个课程是他们的任何特定模式或情节? 谢谢是否可以在javafx对话框中使用特定的类?
答
是的,你可以做到这一点。我的回答是立足于:
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
}
这个想法超出了我的想法,因为我已经使用JAVAFX和JPA之间的适配器模式 –