Javafx:从TableCell获取属性

时间:2017-07-27 09:54:54

标签: java javafx properties javafx-8 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或类似TableView的模型。我有一个带有覆盖TableCell的自定义updateItem,我希望根据CustomProperty具有的属性设置单元格的文本,例如initialValue,oldValue等。示例如果initialValue为0,则将文本设置为空,而不是默认情况下具有单元格的 0 。我有一个部分解决方案:创建一个interface HasCustomProperty然后模型将实现它,但是有一些问题:

  • 我需要将两个CustomProperties或它们的列表添加到界面
  • 我需要在单元格中以某种方式询问:你是appleCount吗?你是桃子细胞吗?

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

我只能获得该项目,这是一种整数,所以我没有它的属性,或者有没有办法获得该属性?

sollution可以在每个列的cellFactory中覆盖updateItem,我知道这是appleColumn所以从appleCountProperty获取信息,依此类推,但是这会导致很多重复的代码如果我必须在5-6个地方做所以我想我创建了一个自定义的TableCell,然后我管理了文本,然后我就为cellFactory()的每个列设置了单元格。

你有什么想法如果没有重复的代码我怎么能这么简单?

1 个答案:

答案 0 :(得分:1)

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

您应该在模型中使用以下内容,而不是使用使用int且不能为null的IntegerProperty:

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

然后在你的表中你绑定它:

@FXML
TableColumn<Model, Integer> appleCountColumn;

//在初始化

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

这应该可以满足您的需求。

相关问题