[英]Is it possible to generate a JavaFX TreeItem's children dynamically based on a function?
我目前正在使用JavaFX中的第一個TreeView
。
文檔中給出的示例如下:
TreeItem<String> root = new TreeItem<String>("Root Node");
root.setExpanded(true);
root.getChildren().addAll(
new TreeItem<String>("Item 1"),
new TreeItem<String>("Item 2"),
new TreeItem<String>("Item 3")
);
TreeView<String> treeView = new TreeView<String>(root);
在這個例子中,我們手動構建TreeItem
樹結構,即在每個有子節點的節點上調用getChildren()
並添加它們。
是否有可能告訴TreeItem
“動態”構建其子項? 如果我可以將父子關系定義為函數,那將是完美的。
我會尋找類似以下的東西:
// Function that generates the child tree items for a given tree item
Function<TreeItem<MyData>, List<TreeItem<MyData>>> childFunction = parent -> {
List<TreeItem<MyData>> children = new ArrayList<>(
parent. // TreeItem<MyData>
getValue(). // MyData
getChildrenInMyData(). // List<MyData>
stream().
map(myDataChild -> new TreeItem<MyData>(myDataChild)))); // List<TreeItem<MyData>>
// The children should use the same child function
children.stream().forEach(treeItem -> treeItem.setChildFunction(childFunction));
return children;
};
TreeItem<MyData> root = new TreeItem<MyData>(myRootData);
root.setExpanded(true);
// THE IMPORTANT LINE:
// Instead of setting the children via .getChildren().addAll(...) I would like to set a "child function"
root.setChildFunction(childFunction);
TreeView<MyData> treeView = new TreeView<String>(root);
由於沒有內置功能(正如@kleopatra在評論中所指出的),我提出了以下TreeItem
實現:
public class AutomatedTreeItem<C, D> extends TreeItem<D> {
public AutomatedTreeItem(C container, Function<C, D> dataFunction, Function<C, Collection<? extends C>> childFunction) {
super(dataFunction.apply(container));
getChildren().addAll(childFunction.apply(container)
.stream()
.map(childContainer -> new AutomatedTreeItem<C, D>(childContainer, dataFunction, childFunction))
.collect(Collectors.toList()));
}
}
用法示例:
Function<MyData, MyData> dataFunction = c -> c;
Function<MyData, Collection<? extends MyData>> childFunction = c -> c.getChildren();
treeTableView.setRoot(new AutomatedTreeItem<MyData, MyData>(myRootData, dataFunction, childFunction));
可能這將有助於未來的某些人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.