Search code examples
javajavafxtableview

TableView Cell skips with the color


The color of the respective cells is not the ones I specified.

Each row with "Online" should be white and each row with "Offline" should be slightly green. This all works, but as soon as I scroll down and up, the ones that are on "Online" get the color green as background color...

Colour of the table

tblIP.setRowFactory(tv -> new TableRow<Device>() {
        @Override
        public void updateItem(Device item, boolean empty) {
            super.updateItem(item, empty);
            if(item == null || empty) {
                setStyle("");
                setText(null);
                this.getStyleClass().add("Offline");
                this.getStyleClass().remove("Online");
                this.getStyleClass().remove("deactive");
            } else if (!item.getActive().get()){
                this.getStyleClass().remove("Offline");
                this.getStyleClass().remove("Online");
                this.getStyleClass().add("deactive");
            } else if (item.getStatus().get() == 1) {
                this.getStyleClass().remove("Offline");
                this.getStyleClass().add("Online");
                this.getStyleClass().remove("deactive");
            } else if (item.getStatus().get() == 0){
                this.getStyleClass().add("Offline");
                this.getStyleClass().remove("Online");
                this.getStyleClass().remove("deactive");
            }
        }
    });

CSS:

.Offline {
    -fx-background-color: rgb(217,153,153);
    -fx-text-fill: black;
}

.Online {
    -fx-background-color: transparent;
    -fx-text-fill: black;
}

.deactive {
    -fx-background-color: rgb(196,215,155);
    -fx-text-fill: black;
}

So that with the color assignment works so far, but that when I scroll that does not color correctly. I guess that I scroll too fast and the "updateItem" does not come behind.


Solution

  • Okey I have solved the problem myself. In that I simply added this.getStyleClass().clear();.

    The Code:

    tblIP.setRowFactory(tv -> new TableRow<Device>() {
            @Override
            public void updateItem(Device item, boolean empty) {
                super.updateItem(item, empty);
                this.getStyleClass().removeAll("deactive", "Online", "Offline"); <- Thanks James_D
                if(item == null || empty) {
                    setStyle("");
                    setText(null);
                } else if (!item.getActive().get()){
                    this.getStyleClass().add("deactive");
                } else if (item.getStatus().get() == 1) {
                    this.getStyleClass().add("Online");
                } else if (item.getStatus().get() == 0){
                    this.getStyleClass().add("Offline");
                }
            }
        });