Issue
So, I have got a list view in JavaFX and I have added a checkbox to each cell.
listView.setCellFactory(CheckBoxListCell.forListView(new Callback<String, ObservableValue<Boolean>>() {
@Override
public ObservableValue<Boolean> call(String item) {
BooleanProperty observable = new SimpleBooleanProperty();
observable.addListener((obs, wasSelected, isNowSelected) -> selected.add(item));
return observable;
}
}));
After I do some processing I need to be able to change the background color for each cell depending on some results (the colors are green/red) I have found a way of doing that:
listView.setCellFactory(list -> {
return new ListCell() {
@Override
protected void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
if (passed.contains(item))
setStyle("-fx-background-color: green; -fx-text-fill: white");
else
setStyle("-fx-background-color: red; -fx-text-fill: white");
setText((String) item);
}
};
});
The problem is that this sets new cells for the list view and removes the checkboxes.
Is it possible somehow to change the background colors and keep the checkboxes?
Solution
You can do:
listView.setCellFactory(list -> new CheckBoxListCell(item -> {
BooleanProperty observable = new SimpleBooleanProperty();
observable.addListener((obs, wasSelected, isNowSelected) ->
selected.add(item)
);
return observable;
}) {
@Override
public void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
if (passed.contains(item)){
setStyle("-fx-background-color: green; -fx-text-fill: white");
setText((String) item);
}else {
setStyle("-fx-background-color: red; -fx-text-fill: white");
setText((String) item);
}
}
});
Answered By - James_D