FXML:绑定到嵌套字段

时间:2016-12-24 21:49:29

标签: javafx binding fxml

我有TableColumn编码为:

<TableColumn text="Nom" prefWidth="${purchasesTable.width*0.65}">
    <cellValueFactory>
        <PropertyValueFactory property="item.name" />
    </cellValueFactory>
</TableColumn>

它的TableView项属性绑定到Purchase类列表:

购买类:

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的其他地方使用它们?

1 个答案:

答案 0 :(得分:2)

PropertyValueFactory不支持“属性属性”。你需要在这里自己实现Callback,这必须在控制器类中完成:

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中,您需要将表列映射到控制器中的字段

<TableColumn fx:id="nameColumn" text="Nom" prefWidth="${purchasesTable.width*0.65}" />