I try do create a customize item within ListView, let's say it's label and I want to execute setCellFactory, while I'm using Label I don't see the item (the text of the label), why?
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();
}
If you do want to show items extending Node there is no need to use custom ListCells. The ListCells of the default factory are doing this already.
However in your case you're calling setItem instead of setGraphic and also you do not set the property back to null, when the cell becomes empty:
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;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With