I'm trying to add background Colors in my Listview via ListCell.
My ListView is working, but I got a problem with the ListCell. It is somehow overwriting the Colors after every ListView item. My current outcome is, that only the last item of my ListView gets the background Color grey (since its Priority is "Neutral"). My suggestion is, that every ListCell overwrites the one before, so that the Colors set before are update to "null" because the priority of the current item is a different one. Does anyone have an idea please?
Edit: I tried Fabians suggestion. I m able to create Notes, but somehow the names of the notes are still the Notepad ID's (i.e. "Notepad@"HexCode""). Also, the Colors are not working. This is the complete methode I'm implementing:
public void initialize() throws SQLException {
//initializing listView
notesListView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
//initializing listView items depending on instance + depending on User
if (this.objectType instanceof Student) {
ObservableList<Notepad> list = FXCollections.observableArrayList();
for(StudentNotepad s : db.getStudentNotepadDao()) {
if(db.getLoggedInUser() == s.getNotepad().getUser()) {
list.add(s.getNotepad());
}
}
notesListView.setItems(list);
notesListView.getItems().clear(); // this is not necessary, if the list is guaranteed to be empty
db.getStudentNotepadDao().queryForAll().stream()
.map(StudentNotepad::getNotepad)
.filter(n -> n.getUser().equals(db.getLoggedInUser()))
.forEach(notesListView.getItems()::add);
notesListView.setCellFactory(new Callback<ListView<Notepad>, ListCell<Notepad>>() {
public ListCell<Notepad> call(ListView<Notepad> param) {
return new ListCell<Notepad>() {
@Override
protected void updateItem(Notepad item, boolean empty) {
super.updateItem(item, empty);
String style = "";
if (!empty && item != null) {
setText(item.getNotepadName());
// this switch could be rewritten using a Map<String, String>
switch (item.getNotepadPriority()) {
case "Hoch":
style = "-fx-background-color: red";
break;
case "Mittel":
style = "-fx-background-color: yellow";
break;
case "Niedrig":
style = "-fx-background-color: green";
break;
case "Neutral":
style = "-fx-background-color: grey";
break;
}
} else {
setText("");
}
setStyle(style);
}
};
}
});
}
}