Javafx:从 TableCell 获取 属性

Javafx: get Property from TableCell

我想从我的 TableCell 中的模型中获取一个 属性,这样我就可以根据它来修改单元格 属性 让我们看下面的例子:

我有一个像这样的模型:

public class Model {

    private CustomProperty<Integer> appleCount;
    private CustomProperty<Integer> peachCount;

    public Model(Integer appleCount, Integer peachCount) {
        this.appleCount = new CustomIntegerProperty(appleCount);
        this.peachCount = new CustomIntegerProperty(peachCount);
    }

    public CustomProperty<Integer> appleCountProperty() {
        return appleCount;
    }

    public CustomProperty<Integer> peachCountProperty() {
        return peachCount;
    }
}

这个模型只是我的模型,我有几个模型有两个或更多 CustomProperty<Integer>

然后我有几张桌子有这个 Model 或类似的 class 作为 TableView 的模型。我有一个带有覆盖 updateItem 的自定义 TableCell,我想根据 CustomProperty 具有的属性设置单元格的文本,例如 initialValue、oldValue、etc.Fo 示例,如果initialValue 为 0 然后将文本设置为空,而不是默认具有单元格的 0。我有一个部分解决方案:创建一个 interface HasCustomProperty 然后模型将实现它,但是有一些问题:

确定一个单元格中只有一个 属性,苹果或桃子,所以理论上我不应该在单元格中关心如果我知道它们都是 CustomIntegerProperties 所以我知道它们有 initialValueoldValue 所以我可以根据它设置单元格的文本。

我只能获取项目,它是一种整数类型,所以我没有它的属性,或者有什么方法可以获取 属性 本身?

一个解决方案可能是在每一列的 cellFactory 中覆盖 updateItem,我知道例如这是 appleColumn,所以从 appleCountProperty 获取信息,等等,但这会导致很多重复代码,如果我必须在 5-6 个地方做。所以我想我制作了一个自定义 TableCell 并在那里管理文本,然后我只是为 cellFactory() 的每个列设置该单元格。

你有什么想法我怎样才能做到简单而不重复代码?

根据我们的讨论 - 我认为您面临的问题是确定 IntegerProperty 的用户集 0 和初始化 0 之间的差异。

与其使用使用 int 且不能为 null 的 IntegerProperty,不如在模型中使用以下内容:

private ObjectProperty<Integer> appleCountProperty = new SimpleObjectProperty<>();

然后在你的 table 中绑定到它:

@FXML
TableColumn<Model, Integer> appleCountColumn;

//在你的初始化中

appleCountColumn.setCellValueFactory(data -> data.getValue().appleCountProperty ());

这应该能满足您的需求。