首页 > 解决方案 > TableView Cell 跳过颜色

问题描述

各个单元格的颜色不是我指定的颜色。

带有“在线”的每一行应该是白色的,带有“离线”的每一行应该是略带绿色的。这一切都有效,但是当我向下和向上滚动时,“在线”上的那些将绿色作为背景色......

桌子的颜色

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;
}

所以到目前为止颜色分配工作,但是当我滚动时颜色不正确。我想我滚动得太快了,“updateItem”没有落后。

标签: javajavafxtableview

解决方案


好的,我自己解决了这个问题。我只是简单地添加了 this.getStyleClass().clear();。

编码:

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");
            }
        }
    });

推荐阅读