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 code lines here, but the main line is the setGraphic() call. It creates an extra graphic element in the list cell:

The setGraphic() method is an entry point to the custom ListView (and other controls with a similar API). You can put anything there; for example, the specialized ListCell classes from the previous sections were implemented using this approach.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.152.139