0

I am trying to implement a custom cellFactory for a ListView. My application is based on this sample I took from another thread.

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;

public class SO extends Application {
    static class XCell extends ListCell<String> {
        HBox hbox = new HBox();
        Label label = new Label("(empty)");
        Pane pane = new Pane();
        Button button = new Button("(>)");
        String lastItem;

        public XCell() {
            super();
            hbox.getChildren().addAll(label, pane, button);
            HBox.setHgrow(pane, Priority.ALWAYS);
            button.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    System.out.println(lastItem + " : " + event);
                }
            });
        }

        @Override
        protected void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            setText(null);  // No text in label of super class
            if (empty) {
                lastItem = null;
                setGraphic(null);
            } else {
                lastItem = item;
                label.setText(item!=null ? item : "<null>");
                setGraphic(hbox);
            }
        }
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        StackPane pane = new StackPane();
        Scene scene = new Scene(pane, 300, 150);
        primaryStage.setScene(scene);
        ObservableList<String> list = FXCollections.observableArrayList(
                "Item 1", "Item 2", "Item 3", "Item 4");
        ListView<String> lv = new ListView<>(list);
        lv.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
            @Override
            public ListCell<String> call(ListView<String> param) {
                return new XCell();
            }
        });
        pane.getChildren().add(lv);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

So for each line of this list will be created a new XCell object from which the hBox will appear. However I don't undertand how the following things occur despite the documentation:

  • this is obscur but I can guess the hBox appears because of ListCell.setgraphics (inherited from the class Labelled).

  • in XCell.updateItem(String item, boolean empty), how are the parameters passed to that method? A call is made for each string contained in the ListView, which returns a new XCell() but no parmeters is passed to that constructor.

Can someone explain that to me?

1 Answer 1

2

this is obscur but I can guess the hBox appears because of ListCell.setgraphics (inherited from the class Labelled).

Yes, that's correct. From the documentation for Cell:

Because by far the most common use case for cells is to show text to a user, this use case is specially optimized for within Cell. This is done by Cell extending from Labeled. This means that subclasses of Cell need only set the text property, rather than create a separate Label and set that within the Cell. However, for situations where something more than just plain text is called for, it is possible to place any Node in the Cell graphic property. Despite the term, a graphic can be any Node, and will be fully interactive. For example, a ListCell might be configured with a Button as its graphic. The Button text could then be bound to the cells item property. In this way, whenever the item in the Cell changes, the Button text is automatically updated.

Your next question:

in XCell.updateItem(String item, boolean empty), how are the parameters passed to that method? A call is made for each string contained in the ListView, which returns a new XCell() but no parmeters is passed to that constructor.

You are setting a factory on the ListView. The factory is essentially a function that creates ListCells for a ListView. So the call(...) method simply has to return a ListCell: in this case you return an instance of your XCell subclass.

The way the ListView works is (conceptually, at least) as follows:

Initially, it uses the cell factory to create ListCells for each of the visible cells, and lays those cells out. It then figures out which value is to be displayed in each of the cells, and calls the updateItem(...) method on each cell, passing in the item. If there is more space than is required for the number of items in the list, it will fill them with additional cells, and call updateItem(null, true) to indicate those cells are empty.

As the items to be displayed change: either by the contents of the list changing, or by the user scrolling around (or by other mechanisms, such as the ListView changing size, etc), the ListView will recompute the items to be displayed and will call updateItem(...) passing in new items. This way the cells can be reused as the user scrolls around and the need to create new cell instances is minimized.

Consequently, when you implement Cells, it is important to respect that fact that the updateItem(...) method may be called many times, while the creation of new Cell instances is relatively rare. So the updateItem(...) method should execute quickly; anything more heavyweight should be done once in the constructor. Notice how in the XCell implementation you show, the creation of all the Nodes (HBox, Label, Pane, and Button), and the layout, is done on construction. The updateItem(...) does this minimal amount of work by just updating the text of the label.

4
  • Would that be possible to "control" which element of ListCell creates a new XCell() ? Like using a for loop, or foreach element in ListCell?
    – kaligne
    Jul 24, 2014 at 17:47
  • I don't understand that comment. In any case, it sounds like a different question, so you should probably clarify it and post it as a new question.
    – James_D
    Jul 24, 2014 at 17:54
  • What I mean is XCell extends a ListCell, so is the extended ListCell a List, as to speak? In the CallBack method, is the ListView associated to one single instance of XCell(), or is it that each element of this ListView is associated to one instance of XCell ?
    – kaligne
    Jul 24, 2014 at 20:43
  • None of those. ListCell is not a list. The ListView creates multiple instances of the XCell, but not necessarily one for every element of the list. (At a minimum it creates one for each visible element of the list, but has the option to reuse existing instances when some elements become invisible and others become visible, for example when the user scrolls.)
    – James_D
    Jul 24, 2014 at 20:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.