动态更改 ListView 中单元格的背景

Dynamically change the background of a cell in a ListView

我的列表视图有问题。 我有一些代码可以更改 ListView 中某些单元格的背景。但是当我在该列表视图中滚动时,背景更改为错误的单元格。

在这里你可以看到一些代码: 更改列表视图中单元格的背景:

@Override
        public ListCell<String> call(ListView<String> param) {
            ListCell<String> cell = new ListCell<String>() {
                @Override
                protected void updateItem(String t, boolean bln) {
                    super.updateItem(t, bln);
                    if (t != null) {
                        setText(t);

                        if (!controller.checkGerecht(t)) {

                           if (!getStyleClass().contains("mystyleclass")) {
                                getStyleClass().add("mystyleclass");
                                foutieveInput.add(t);
                            } else {      
                               getStyleClass().remove("mystyleclass");
                            }
                        } else {
                            setText(t);

                        }
                    }
                }

css 文件:

.mystyleclass{
    -fx-background-color: #ff0000;
}

您的逻辑实现不正确,假设您只想在 controller.checkGerecht(t)false 的单元格上使用红色背景。如果样式 class 不存在,您正在尝试删除它:如果您的条件不成立,您想删除样式 class。 (即你在错误的 else 子句中有 remove。)

此外,您需要处理更新单元格以保存 null 值(例如,如果它为空)的情况:

public ListCell<String> call(ListView<String> param) {
    ListCell<String> cell = new ListCell<String>() {
        @Override
        protected void updateItem(String t, boolean bln) {
            super.updateItem(t, bln);
            if (t == null) {
                setText(null);
                getStyleClass().remove("mystyleclass");
            } else {
                setText(t);

                if (!controller.checkGerecht(t)) {

                    if (!getStyleClass().contains("mystyleclass")) {
                        getStyleClass().add("mystyleclass");
                        foutieveInput.add(t);
                    } 
                } else {
                    getStyleClass().remove("mystyleclass");
                }
            }

        }
    };
    return cell ;
}