我正在搜索javafx JOptionPane等价物,我确实找到了一个伟大的类Dialog。所以在本教程中,导师使用:Dialog<Pair<String,String>>
来获取两个String输入字段,从这里我想知道是否可以使用一个类来说:Dialog<Product>
。如果可能的话我应该怎么写这个类是他们的任何特定模式或情节呢?
感谢
答案 0 :(得分:2)
是的,你可以这样做。我的回答是基于:
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
}