我尝试在ListView中创建一个自定义项目,假设它是标签,并且我想执行setCellFactory,而我在使用Label时却看不到该项目(标签的文本),为什么?
ListView<Label> list = new ListView<Label>();
ObservableList<Label> data = FXCollections.observableArrayList(
new Label("123"), new Label("45678999"));
@Override
public void start(Stage stage) {
VBox box = new VBox();
Scene scene = new Scene(box, 200, 200);
stage.setScene(scene);
stage.setTitle("ListViewExample");
box.getChildren().addAll(list);
VBox.setVgrow(list, Priority.ALWAYS);
list.setItems(data);
list.setCellFactory(new Callback<ListView<Label>, ListCell<Label>>() {
@Override
public ListCell<Label> call(ListView<Label> list) {
ListCell<Label> cell = new ListCell<Label>() {
@Override
public void updateItem(Label item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setItem(item);
}
}
};
return cell;
}
}
);
stage.show();
}
解决方法:
如果确实要显示扩展Node的项目,则无需使用自定义ListCell.默认工厂的ListCell已在执行此操作.
但是,在这种情况下,您将调用setItem而不是setGraphic,并且在单元格变为空时,也不要将属性设置回null:
list.setCellFactory(new Callback<ListView<Label>, ListCell<Label>>() {
@Override
public ListCell<Label> call(ListView<Label> list) {
ListCell<Label> cell = new ListCell<Label>() {
@Override
public void updateItem(Label item, boolean empty) {
super.updateItem(item, empty);
// also sets to graphic to null when the cell becomes empty
setGraphic(item);
}
};
return cell;
}
});