首先注意你的单元实现有一个bug。您需要必须处理updateItem(...)
方法中的所有可能性。在您的实现中,如果单元格当前显示一个项目,然后作为空单元格重用(例如,如果项目被删除),那么单元格将不会清除其文本。
可以显著减少代码量如果实现了Callback
作为lambda表达式,而不是匿名内部类:
myList.setCellFactory(lv -> new ListCell<MyCustomData>() {
@Override
protected void updateItem(MyCustomData item, boolean empty) {
super.updateItem(item, empty);
setText(item == null ? null : item.getMyProperty());
}
});
如果你是做了很多这方面,并希望减少代码量进一步,这不是努力创造一个可重复使用的通用电池工厂实现:
public class ListViewPropertyCellFactory<T>
implements Callback<ListView<T>, ListCell<T>> {
private final Function<T, String> property ;
public ListViewPropertyCellFactory(Function<T, String> property) {
this.property = property ;
}
@Override
public ListCell<T> call(ListView<T> listView) {
return new ListCell<T>() {
@Override
protected void updateItem(T item, boolean empty) {
super.updateItem(item, boolean);
setText(item == null ? null : property.apply(item));
}
};
}
}
,你可以用
使用
如果你喜欢一个更实用的风格,以创建实现Callback
一类,你可以做同样
public class ListViewPropertyCellFactory {
public static <T> Callback<ListView<T>, ListCell<T>> of(Function<T, String> property) {
return lv -> new ListCell<T>() {
@Override
protected void updateItem(T item, boolean empty) {
super.updateItem(item, boolean) ;
setText(item == null ? null : property.apply(item));
}
};
}
}
和
myList.setCellFactory(ListViewPropertyCellFactory.of(MyCustomData::getMyProperty));