gpt4 book ai didi

treeview - Javafx 2 TreeView 过滤

转载 作者:行者123 更新时间:2023-12-02 07:59:57 30 4
gpt4 key购买 nike

如何在 JavaFX 2 TreeView 中过滤节点?

我有一个 TextField,我想根据 TextField 的内容过滤所有节点(例如节点标签)。

谢谢。

最佳答案

这是我编写的可重用的可过滤树项目类。

过滤器应该绑定(bind)在predicateProperty上,并且您必须使用getSourceChildren方法来操作树项。

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

}

关于treeview - Javafx 2 TreeView 过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15897936/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com