如何通过名称而不是值获取 TreeView 分支?
How can I get a TreeView branch by name rather than value?
有什么方法可以通过名称获得 TreeView
分支?
例如,如果我有一个像这样的 TreeView
菜单:
TreeItem<String> root, branch;
root = new TreeItem<>();
root.setExpanded(true);
branch = makeBranch("Chicken", root);
makeBranch("Hen", branch);
这里是 makeBranch()
方法:
public TreeItem<String> makeBranch(String s, TreeItem<String> parent){
TreeItem<String> item = new TreeItem<>(s);
item.setExpanded(true);
parent.getChildren().add(item);
return item;
}
现在如果我想开分店,我可以这样做:
branch.getChildren().get(a_number); // get using index
但是无论如何我可以通过名称而不是值来获得分支吗?
所以像:
branch.getChildren().get("the name of leaf or branch");
自TreeItem.getChildren()
returns a ObservableList<TreeItem<T>>
, you can use the methods of List
to find the child you're looking for, e.g. using Stream
过滤内容:
final String value = "the name of leaf or branch";
Optional<TreeItem<String>> nodeOptional = branch.getChildren().stream()
.filter(
(child)-> child.getValue().equals(value)
)
.findFirst();
if (nodeOptional.isPresent()) {
TreeItem<String> item = nodeOptional.get();
// do something with item
} else {
// no child with specified value was found
}
请注意,您只能以这种方式搜索 branch
的 直接 子级。如果你想找到 branch
的任意后代,你必须做 tree search.
有什么方法可以通过名称获得 TreeView
分支?
例如,如果我有一个像这样的 TreeView
菜单:
TreeItem<String> root, branch;
root = new TreeItem<>();
root.setExpanded(true);
branch = makeBranch("Chicken", root);
makeBranch("Hen", branch);
这里是 makeBranch()
方法:
public TreeItem<String> makeBranch(String s, TreeItem<String> parent){
TreeItem<String> item = new TreeItem<>(s);
item.setExpanded(true);
parent.getChildren().add(item);
return item;
}
现在如果我想开分店,我可以这样做:
branch.getChildren().get(a_number); // get using index
但是无论如何我可以通过名称而不是值来获得分支吗? 所以像:
branch.getChildren().get("the name of leaf or branch");
自TreeItem.getChildren()
returns a ObservableList<TreeItem<T>>
, you can use the methods of List
to find the child you're looking for, e.g. using Stream
过滤内容:
final String value = "the name of leaf or branch";
Optional<TreeItem<String>> nodeOptional = branch.getChildren().stream()
.filter(
(child)-> child.getValue().equals(value)
)
.findFirst();
if (nodeOptional.isPresent()) {
TreeItem<String> item = nodeOptional.get();
// do something with item
} else {
// no child with specified value was found
}
请注意,您只能以这种方式搜索 branch
的 直接 子级。如果你想找到 branch
的任意后代,你必须做 tree search.