Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listview setCellFactory with generic label

Tags:

java

javafx

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();
}
like image 894
Roy Shmuli Avatar asked Oct 17 '22 20:10

Roy Shmuli


1 Answers

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;
    }
});
like image 112
fabian Avatar answered Oct 21 '22 04:10

fabian