问题
I have got a ObservableList
and I linked it to multiple CheckMenuItem
it's shown in a TableView
and I can filter out one predicate.
I did that by using .filter(Predicate p)
and updated my TableView
to it's return value. When I wanted to unfilter, I simply set it back on my ObservableList
.
But I can't wrap my head around on how to remove multiple filteres to my ObservableList
. I can apply them if i just keep using .filter(Predicate p)
with different predicates on the returned lists, but how to I remove a spcific filter?
Greets
回答1:
The code
ObservableList<DataType> data = FXCollections.observableArrayList();
table.setItems(data.filter(predicate));
is equivalent to
ObservableList<DataType> data = FXCollections.observableArrayList();
table.setItems(new FilteredList<DataType>(data, predicate));
and the code
ObservableList<DataType> data = FXCollections.observableArrayList();
table.setItems(data.filter(predicate1).filter(predicate2));
is logically equivalent to
ObservableList<DataType> data = FXCollections.observableArrayList();
table.setItems(new FilteredList<DataType>(data, predicate1.and(predicate2)));
So you can achieve what you need by keeping a reference to the filtered list and updating its predicate:
ObservableList<DataType> data = FXCollections.observableArrayList();
FilteredList<DataType> filteredData = new FilteredList<>(data, x -> true);
table.setItems(filteredData);
Now you can use predicate1
only with:
filteredData.setPredicate(predicate1);
add predicate2
:
filteredData.setPredicate(predicate1.and(predicate2));
remove predicate1
:
filteredData.setPredicate(predicate2);
remove all filters:
filteredData.setPredicate(x -> true);
If you wanted a really esoteric solution (which is almost certainly overkill), you could keep an ObservableList<Predicate<DataType>>
:
ObservableList<Predicate<DataType>> filters = FXCollections.observableArrayList();
and then bind the predicate of the filtered list to combining all filters with a logical and
:
filteredList.predicateProperty().bind(Bindings.createObjectBinding(() ->
filters.stream().reduce(x -> true, Predicate::and),
filters));
Then you can just add and remove predicates to the filters
list, e.g.
filters.add(predicate1);
filters.add(predicate2);
filters.remove(predicate1);
and the table data will automatically update.
来源:https://stackoverflow.com/questions/44920582/javafx-unfilter-filteredlist