JavaFX unfilter FilteredList

陌路散爱 提交于 2019-12-25 09:39:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!