FXML:绑定到嵌套字段 [英] FXML: Bind to nested field
问题描述
我有 TableColumn
编码为:
<TableColumn text="Nom" prefWidth="${purchasesTable.width*0.65}">
<cellValueFactory>
<PropertyValueFactory property="item.name" />
</cellValueFactory>
</TableColumn>
它的 TableView
的items属性被绑定到购买
类列表:
it's TableView
's items property is bound to a list of Purchase
class:
购买类:
public class Purchase {
private Item item;
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
}
我的 Item
类如下:
public class Item {
private long id;
private StringProperty name = new SimpleStringProperty();
private DoubleProperty price = new SimpleDoubleProperty();
//Getters and Setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public final StringProperty nameProperty() {
return this.name;
}
public final String getName() {
return this.nameProperty().get();
}
public final void setName(final String name) {
this.nameProperty().set(name);
}
}
当我将购买添加到我的表时,名称单元格不会出现。我究竟做错了什么?我的 Item
字段是否需要作为属性,因为我想在不使用JavaFX的其他地方使用它们?
when I add Purchases to my table the name cell do not appear. What am I doing wrong? and is it necessary to my Item
fields as properties, because I want to use them somewhere else where JavaFX is not used?
推荐答案
PropertyValueFactory
不支持属性属性。你需要在这里自己实现 Callback
,这必须在控制器类中完成:
PropertyValueFactory
does not support "properties of properties". You need to implement the Callback
yourself here, which has to be done in the controller class:
public class MyController {
@FXML
private TableColumn<Purchase, String> nameColumn ;
public void initialize() {
nameColumn.setCellValueFactory(cellData -> {
String name ;
Purchase purchase = cellData.getValue();
if (purchase == null) {
name = null ;
} else {
name = purchase.getName();
}
return new SimpleStringProperty(name);
});
// ...
}
// ...
}
然后在fxml中,你需要将表格列映射到控制器中的字段
and then in the fxml, of course, you need to map the table column to the field in the controller
<TableColumn fx:id="nameColumn" text="Nom" prefWidth="${purchasesTable.width*0.65}" />
这篇关于FXML:绑定到嵌套字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!