【发布时间】:2019-05-03 09:40:47
【问题描述】:
我正在尝试通过 ListCell 在我的 Listview 中添加背景颜色。
我的 ListView 工作正常,但 ListCell 出现问题。它以某种方式覆盖每个 ListView 项目之后的颜色。我目前的结果是,只有我的 ListView 的最后一项获得背景颜色灰色(因为它的优先级是“中性”)。我的建议是,每个 ListCell 都覆盖之前的一个,以便之前设置的颜色更新为“null”,因为当前项目的优先级不同。 请问有人有什么想法吗?
编辑: 我尝试了费边的建议。我可以创建笔记,但不知何故,笔记的名称仍然是记事本 ID(即“Notepad@”HexCode“”)。此外,颜色不起作用。这是我正在实施的完整方法:
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);
}
};
}
});
}
}
【问题讨论】:
标签: listview javafx background-color