0
votes

I have a TableView with some records and want to set the background color of a cell depending on a property (eg. set color if ID == 5).

Basically that works.

See Image 1

public class CustomCell extends TableCell<Person, String> {

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

    if (item != null && !empty){

        setText(item);

        if (getTableRow() != null && getTableRow().getItem() != null){
            Person p = (Person) getTableRow().getItem();

            if (p.getId() == 5){
                setStyle("-fx-background-color: #CBDBD7;");
            }
        }
    }else{
        setText(null);
    }
}

But when i start to scroll up and down a few times, different cells get the background color as well. This is not the behavior i want.

Wrong cells with background color

I tested this on macOS 10.13.1 / Java 1.8.0_151 and Debian with OpenJDK.

https://github.com/glueckandi/test_fx.git

What am I doing wrong?

1
You're not removing the background color when another item that does not match your criterion is placed in the cell. - fabian

1 Answers

0
votes

Try setting the style to null or "" empty string.

if (p.getId() == 5)
{
    setStyle("-fx-background-color: #CBDBD7;");    
}
else
{
    setStyle("");
}

and

else
{
    setText(null);
    setStyle("");
}