我尝试在 ListView
中创建一个自定义项,假设它是标签,我想在使用 Label
时执行 setCellFactory
> 我没有看到项目(标签的文本),为什么?
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;
}
});
关于java - 带有通用标签的 Listview setCellFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41319752/