Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javafx 2 TreeView Filtering

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.

like image 231
Tex'N'Duet Avatar asked Apr 09 '13 09:04

Tex'N'Duet


2 Answers

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;
    }

}
like image 197
kaznovac Avatar answered Nov 02 '22 00:11

kaznovac


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.

like image 38
Alexander Kirov Avatar answered Nov 01 '22 23:11

Alexander Kirov