How is it possible to filter Nodes in a JavaFX 2 TreeView
?
I have a TextField
and I want to filter all Nodes (for example node labels) based on the content of the TextField
.
Thanks.
this is reusable filterable tree item class i've wrote.
the filter should be bound on predicateProperty, and you must use getSourceChildren method to manipulate tree items.
public class FilterableTreeItem<T> extends TreeItem<T> {
private final ObservableList<TreeItem<T>> sourceChildren = FXCollections.observableArrayList();
private final FilteredList<TreeItem<T>> filteredChildren = new FilteredList<>(sourceChildren);
private final ObjectProperty<Predicate<T>> predicate = new SimpleObjectProperty<>();
public FilterableTreeItem(T value) {
super(value);
filteredChildren.predicateProperty().bind(Bindings.createObjectBinding(() -> {
Predicate<TreeItem<T>> p = child -> {
if (child instanceof FilterableTreeItem) {
((FilterableTreeItem<T>) child).predicateProperty().set(predicate.get());
}
if (predicate.get() == null || !child.getChildren().isEmpty()) {
return true;
}
return predicate.get().test(child.getValue());
};
return p;
} , predicate));
filteredChildren.addListener((ListChangeListener<TreeItem<T>>) c -> {
while (c.next()) {
getChildren().removeAll(c.getRemoved());
getChildren().addAll(c.getAddedSubList());
}
});
}
public ObservableList<TreeItem<T>> getSourceChildren() {
return sourceChildren;
}
public ObjectProperty<Predicate<T>> predicateProperty() {
return predicate;
}
}
There is no special filter, provided by JFX.
So you should implement it by yourself.
The only support from JFX you have - tracking of collection of TreeItems' items. When you add or remove an item, it will be added or removed. But adding or removing from collections you implement yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With