我正在尝试使用其中的文本字段创建Dialog。代码如下:
private void showBatchDialog() {
Dialog<Batch> dialog = new Dialog<Batch>();
dialog.setTitle("Add batch");
dialog.setHeaderText("adding new batch");
ButtonType addButtonType = new ButtonType("Add batch",
ButtonData.OK_DONE);
Collection<ButtonType> buttons = new ArrayList<ButtonType>();
buttons.add(addButtonType);
buttons.add(ButtonType.CANCEL);
dialog.getDialogPane().getButtonTypes().addAll(buttons);
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 150, 10, 10));
TextField code = new TextField();
code.setPromptText("code");
TextField name = new TextField();
name.setPromptText("name");
grid.add(new Label("code"), 0, 0);
grid.add(code, 1, 0);
grid.add(new Label("name"), 0, 1);
grid.add(name, 1, 1);
dialog.getDialogPane().setContent(grid);
dialog.setResultConverter(value -> {
if (value == addButtonType) {
return new Batch() {
{
setCode(code.getText());
setName(name.getText());
}
};
} else {
return null;
}
});
Optional<Batch> result = dialog.showAndWait();
result.ifPresent(consumer -> {
Batch batch = (Batch) consumer;
batch.getClass(); // Doesn't returns Batch class
});
}
因此,当我尝试通过对话框类返回时,它不会返回Batch。问题是如何获得Batch class?
Batch类的主体如下
@Entity
public class Batch {
@Id
@GeneratedValue(generator="uuid")
@GenericGenerator(name="uuid", strategy="uuid2")
@Column(name="batch_id")
private String uuid;
@NotNull(message="Code field could not be an empty")
@Column(unique=true)
private String code;
private String name;
@OneToMany(mappedBy = "batch", cascade = CascadeType.ALL)
private Collection<Product> products = new ArrayList<Product>();
public Collection<Product> getProducts() {
return products;
}
public void setProducts(Collection<Product> products) {
this.products = products;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
答案 0 :(得分:1)
您创建扩展Batch
的匿名类的实例。替换您的if
声明
if (value == addButtonType) {
return new Batch() {
{
setCode(code.getText());
setName(name.getText());
}
};
}
使用以下代码:
if (value == addButtonType) {
Batch b = new Batch();
b.setCode(code.getText());
b.setName(name.getText());
return b;
}
答案 1 :(得分:-1)
在java中,对象的getClass()方法返回Class<? extends Object>
,因此您不希望得到Batch
作为此代码的结果 - 相反,您应该期望一个实例类。