I have a problem with my listview. I have some code that changes the background of some cells in a ListView. But when i scroll in that listview the background changes to the wrong cells.
Here you see some code: Change the background of the cell in a 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);
}
}
}
The css file:
.mystyleclass{
-fx-background-color: #ff0000;
}
You have the logic implemented incorrectly, assuming you want the red background only on cells for which controller.checkGerecht(t)
is false
. You're trying to remove the style class if it's not present: you want to remove the style class if your condition doesn't hold. (I.e. you have remove
in the wrong else
clause.)
Additionally, you need to handle the case where the cell is updated to hold a null
value (e.g. if it is empty):
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 ;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments