Dmig
Dmig

Reputation: 266

JavaFx ListView doesn't show text, but working after cellFactory

I have a ListView with click listener. I want add new listener on hover. I coded that new listener with CellFactory (code below). Only with this code my ListView (<String>) show items without text but both listeners works fine (click listener works fine anyway) and items properly selected.

Code of CellFactory in Controller's initialize():

myListView.setCellFactory(lv -> {
        ListCell<String> cell = new ListCell<String>() {};
        cell.hoverProperty().addListener((obs, wasHovered, isNowHovered) -> {
        if(isNowHovered) {
            handleCellHover(cell);
        } else {
            handleCellHoverEnd();
        }
    });
    return cell;
});

Code of adding elements:

// ...
ObservableList<String> data = FXCollections.observableArrayList(data); //data is List<String>
listView.setItems(data);

Upvotes: 1

Views: 276

Answers (1)

fabian
fabian

Reputation: 82461

ListCell.updateItem by default does nothing but assign the item and empty properties. You need to override this method to use the item for modifying the cell's look, e.g. by setting the text property:

ListCell<String> cell = new ListCell<String>() {
    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);

        if (empty || item == null) {
            setText("");
        } else {
            setText(item);
        }
    }
};

(The default cellFactory uses a subclass of ListCell with a similar updateItem implementation.)

Upvotes: 3

Related Questions