我的 ListView 有问题。 我有一些代码可以更改 ListView 中某些单元格的背景。但是当我在该 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
的单元格上使用红色背景。如果样式类不存在,您将尝试删除它:如果您的条件不成立,您希望删除样式类。 (即,您在错误的 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 ;
}
关于java - 动态更改 ListView 中单元格的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32908349/