Javafx 2 TreeView Filtering

How can I filter nodes in a JavaFX 2 TreeView ?

I have a TextField and I want to filter out all nodes (e.g. node labels) based on the contents of the TextField .

Thanks.

+4
source share
2 answers

There is no special filter provided by JFX.

So you have to implement it yourself.

The only JFX support you have is tracking a collection of TreeItems. When you add or remove an item, it will be added or deleted. But adding or removing from collections that you implement yourself.

+1
source

this is the reusable filtered class of tree elements that I wrote.

the filter must be bound to predicateProperty, and you must use the getSourceChildren method to control the elements of the tree.

 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; } } 
+5
source

All Articles