Creating custom cells

Another role of Cell Factory is creating custom cells for your list with any content, instead of text.

In the following setCellFactory method, we will add a color rectangle corresponding to the list-item name:

ObservableList<String> items = FXCollections.observableArrayList(        "Red", "Blue", "Yellow", "Green");ListView<String> list = new ListView<>(items);list.setCellFactory((ListView<String> param) -> {    return new ListCell<>() {        @Override        public void updateItem(String item, boolean empty) {            super.updateItem(item, empty);            if (! (empty || item == null)) {                // adding new item                setGraphic(new Rectangle(30, 30, Color.web(item)));                setText(item);            } else {                setText(null);                setGraphic(null);            }        }    };});

There are quite a few plumbing ...

Get Mastering JavaFX 10 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.