marcin panek
marcin panek

Reputation: 117

rows color javafx listview

I have a problem with ListView control. I want to my odd and even rows have different colours but I want do it from code not from FXML. For example:

For now I have something like this but this changed background of all ListView not single row.

rightListView.setCellFactory(param -> new ListCell<Group>() {
        @Override
        protected void updateItem(Group item, boolean empty) {
            super.updateItem(item, empty);

            if (empty || item == null || item.getName() == null) {
                setText(null);
            } else {
                setText(item.getName());
            }
            for(int k=0;k<rightListView.getItems().size();k++) {
                if (k%2==0)
                    setStyle("-fx-background-color: blue;");
                else
                    setStyle("-fx-background-color: red;");
            }
        }
    });

How can I solve this?

Upvotes: 3

Views: 5556

Answers (1)

fabian
fabian

Reputation: 82451

The simplest way of achieving this result would be a CSS stylesheet:

scene.getStylesheets().add("style.css");

style.css

.list-view .list-cell:odd {
    -fx-background-color: red;
}

.list-view .list-cell:even {
    -fx-background-color: blue;
}

You may need to replace the .list-view selector with a selector selecting the ListView this style should be applied to. This has the benefit that it allows you to keep the :selected style much easier than with code.

.list-view .list-cell:odd {
    -fx-background-color: red;
}

.list-view .list-cell:even {
    -fx-background-color: blue;
}

.list-view .list-cell:selected:odd,
.list-view .list-cell:selected:even {
    -fx-background-color: -fx-background;
}

If you want to apply the style using setStyle in your java code though, you should use getIndex in updateItem:

rightListView.setCellFactory(param -> new ListCell<Group>() {
    @Override
    protected void updateItem(Group item, boolean empty) {
        super.updateItem(item, empty);

        if (empty || item == null) {
            setText(null);
            setStyle(null);
        } else {
            setText(item.getName());
            setStyle(getIndex() % 2 == 0 ? "-fx-background-color: blue;" : "-fx-background-color: red;");
        }
    }
});

Upvotes: 7

Related Questions