user2211907
user2211907

Reputation:

TableCell css class not updating on scroll in TableView

I have a TableView and I am trying to make it so that when I click on a row, all of the rows above will change their style (turn gray). I created a custom TableCell, and its updateItem method is shown below. The .row-to-ignore CSS class has a few !important properties.

On each updateItem, I check whether the row index is above or below a certain threshold, and then either apply or remove a style class.

Everything works fine until I scroll; when I scroll up, everything gets the style applied to like it should. However, when I scroll down, random lines have the style applied, and others don't.

The odd thing is that if I apply the style using setStyle(), everything works correctly.

Custom Table Cell snippet:

@Override protected void updateItem(String cellItem, boolean empty) {
    super.updateItem(cellItem, empty);

    if (cellItem != null) {
        setText(cellItem);

        // Apply styling depending on whether the row is selected as not-data.
        if ((this.getTableRow().getIndex()) < mHighlightIndex)
        {
            // Apply "ignore" styling.
            this.getStyleClass().add("row-to-ignore");
        } else {
            // Remove ignore styling.
            this.getStyleClass().remove(".row-to-ignore");
        }
    } else {
        setText("");
    }
}

CSS file:

.row-to-ignore {
    -fx-background-color: #e3e4e9 !important;
    -fx-text-fill: #b8b8b8 !important;
}

Upvotes: 1

Views: 402

Answers (1)

user2211907
user2211907

Reputation:

I found my answer in this post. It turns out that I was adding multiple copies of the class to the list with the style class. Removing all of the copies of the class made the issue go away.

I changed this:

// Apply "ignore" styling.
this.getStyleClass().add("row-to-ignore");

to this:

// Apply "ignore" styling. Make sure not to add duplicate copies of class to style list.
if (!this.getStyleClass().contains("row-to-ignore")) {
    this.getStyleClass().add("row-to-ignore");
}

Upvotes: 4

Related Questions