alex
alex

Reputation: 5684

JavaFX ListView - CellFactory styling

I'm using a ListView with a CellFactory producing Labels for each list entry. When a list entry is selected, the text of the Labels becomes white no matter what CSS style i set for list-view or list-cell.

How can i controll the color/ styling behaviour of Labels used by a CellFactory aka ListCell?

items.addAll(Arrays.asList("Test 1","Test 2","Test 3"));
lstPreview.setItems(items);
lstPreview.setCellFactory(i -> new ListCell<String> () {
            @Override
            protected void updateItem (String item,boolean empty){
                super.updateItem(item, empty);
                if (item == null || empty) {
                    setText(null);
                } else {
                    setGraphic(new Label(item));
                }
            }

    });

Upvotes: 1

Views: 3480

Answers (1)

ItachiUchiha
ItachiUchiha

Reputation: 36722

You can apply css to the label, when the list-cell is getting selected.

For a selected list-cell, the css is

.list-cell:filled:selected {
    ...
}

For a selected list-cell, which has a label, we can write

.list-cell:filled:selected .label {
    ...
}

To color the label, you can use -fx-text-fill

.list-cell:filled:selected .label {
    -fx-text-fill: red;
}

You can use the same way if it the content is any other node other than Label.

The output is as follows

enter image description here

EDIT

If you just want to override the default white color, you can override the .label on selected.

.list-cell:filled:selected .label {
    -fx-text-fill: black ;
}

Upvotes: 3

Related Questions