user3237736
user3237736

Reputation: 857

JavaFX ListView: custom Font not applied properly

I got a ListView in my JavaFX App, where I set up a custom cell renderer as follows:

    myListView.setCellFactory((params) -> new MyListRenderer());

The renderer class:

class MyListRenderer extends ListCell<MyItemClass> {

    private final Label text;

    MyListRenderer() {
        text = new Label();
        text.setFont(Font.font("Monospaced", 12));
    }

    @Override
    protected void updateItem(MyItemClass item, boolean empty) {
        super.updateItem(item, empty);
        if (item == null || empty) {
            setGraphic(null);
            setText(null);
        } else {
            if(item.isSpecialItem()){
                text.setText("\u25B6 " + item.getString();
                text.setStyle("-fx-font-weight: bold;");
            } else {
                text.setText(item.getString());
                text.setStyle("-fx-font-weight: normal;");
            }
            setGraphic(text);
        }
    }
}

As you can see I set the font to be Monospaced, and also I set the text and the style according to a flag of my items ('isSpecialItem')

So, it works fine at first, when I add the first few entries they are rendered correctly. However as soon as I select any entry in the list, the Font of my text label gets reset to the default font of list cells. Interestingly enough, only the font seems to be reset, as both the text I set as well as the style (bold or normal) are still applied correctly.

I tried to put this line:

text.setFont(Font.font("Monospaced", 12));

in the updateItem method, so that it gets re-executed on every update. However, it still doesn't work, as I noticed that the method is not even called when I select items.

So finally, the problem is this: On selection in the list view, the font gets reset for some reason, and the updateItem method is not even called again so I cannot set it back to the desired font.

Anyone knows what's going on here and how I can fix it?

Thanks

Upvotes: 1

Views: 997

Answers (1)

MBec
MBec

Reputation: 2210

Use CSS file and set font family and font size to .list-cell:

.list-cell {
    -fx-font-family: "Monospaced";
    -fx-font-size: 12px;
}

EDIT

Answering your question in comment: Yes that code will change all list cell in your application.

You can create your own style class selector to specific list cell or ID style selector. See Skinning JavaFX Applications with CSS and JavaFX CSS Reference Guide, there are simple examples how to create them.

In your case CSS file:

.custom-list-cell {
    -fx-font-family: "Monospaced";
    -fx-font-size: 12px;
}

and MyListRenderer class:

MyListRenderer() {
    getStyleClass().add("custom-list-cell");
    text = new Label();
}

Note that this will change fonts in all Labeled components in custom ListCell.

Upvotes: 1

Related Questions