[英]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
单元格上显示红色背景,则逻辑实现不正确。 您尝试删除样式类(如果不存在):如果条件不成立,则要删除样式类。 (即您remove
了错误的else
子句。)
此外,您需要处理将单元格更新为保留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 ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.