如何在按钮单击后永久更改列表视图中所选项目的颜色?
apsentButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
}
});
所以,我有apsentButton和listview,我想当我从listview中选择某个项目并单击按钮时,该选定视图永久变为绿色,而在listview中单击其他项目后,我希望我先选择该项目保持绿色????
答案 0 :(得分:0)
将选定的项目保存在可观察的集合中,并使用cellFactory
返回的单元格,这些单元格会随着项目的更改或列表的更新而更新。要根据选择/焦点状态选择不同的颜色,最好使用CSS样式表和PseudoClass
进行样式设置:
final PseudoClass marked = PseudoClass.getPseudoClass("marked");
final ListView<String> listView = new ListView<>();
for (int i = 1; i <= 100; i++) {
listView.getItems().add("item " + i);
}
final ObservableSet<String> markedItems = FXCollections.observableSet(new HashSet<>());
Button button = new Button("mark");
button.setOnAction(evt -> markedItems.addAll(listView.getSelectionModel().getSelectedItems()));
listView.setCellFactory(lv -> new ListCell<String>() {
final InvalidationListener l = o -> {
String item = getItem();
pseudoClassStateChanged(marked, item != null && markedItems.contains(item));
};
final WeakInvalidationListener listener = new WeakInvalidationListener(l);
{
markedItems.addListener(listener);
}
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(item);
l.invalidated(null);
}
});
样式表已应用于祖先/场景:
.list-cell:marked {
-fx-base: green;
-fx-selection-bar: #00FFFF;
-fx-selection-bar-non-focused: #228822;
}