2017-06-16 97 views
0

我在我的FXML文件中定义了一个ListView,该文件将保存MyCustomData对象。我可以找出如何告诉它,以显示其MyCustomData财产的唯一方法是将以下代码添加到我的控制器:如何指定使用自定义对象时JavaFX ListView应显示的属性?

myList.setCellFactory(new Callback<ListView<MyCustomData>, ListCell<MyCustomData>>() { 
    @Override 
    public ListCell<MyCustomData> call(ListView<MyCustomData> param) { 
     return new ListCell<MyCustomData>() { 
      @Override 
      protected void updateItem(MyCustomData item, boolean empty) { 
       super.updateItem(item, empty); 
       if(item != null) { 
        setText(item.getMyProperty()); 
       } 
      } 
     }; 
    } 
}); 

这肯定将是很好用单来代替这一切乱码在FXML中指定应显示的属性。这可能吗?

回答

1

首先注意你的单元实现有一个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)); 
相关问题