如何在JavaFX中获得父节点中的所有节点? [英] How do I get all nodes in a parent in JavaFX?
问题描述
在C#中,我发现了一种非常漂亮的方法,该方法使您可以从指定控件中获取所有后代和所有THEIR后代.
In C# I found a method that was pretty sweet that allowed you to get all the descendants and all of THEIR descendants from a specified control.
我正在寻找类似的JavaFX方法.
I'm looking for a similar method for JavaFX.
我看到了Parent
类是我要使用的类,因为它是派生所有带有孩子的Node类的类.
I saw that the Parent
class is what I want to work with since it is the class from which all Node classes that bear children are derived.
这是我到目前为止的结果(并且我还没有在Google上通过"JavaFX从场景中获取所有节点"之类的搜索真正找到任何东西):
This is what I have so far (and I haven't really found anything on google with searches like "JavaFX get all nodes from a scene"):
public static ArrayList<Node> GetAllNodes(Parent root){
ArrayList<Node> Descendents = new ArrayList<>();
root.getChildrenUnmodifiable().stream().forEach(N -> {
if (!Descendents.contains(N)) Descendents.add(N);
if (N.getClass() == Parent.class) Descendents.addAll(
GetAllNodes((Parent)N)
);
});
}
那么我如何确定N是否是父母(或从父母继承)?我说的对吗?它似乎不起作用...它正在从根(父)节点中获取所有节点,而不是从其中具有子节点的节点中获取所有节点.我觉得这也许可以解决这个问题,但我只是在问一个问题……错了.我该怎么做呢?
So how do I tell if N is a parent (or extended from a parent)? Am I doing that right? It doesn't seem to be working... It's grabbing all the nodes from the root (parent) node but not from the nodes with children in them. I feel like this is something that's probably got an answer to it but I'm just asking the question... wrong. How do I go about doing this?
推荐答案
public static ArrayList<Node> getAllNodes(Parent root) {
ArrayList<Node> nodes = new ArrayList<Node>();
addAllDescendents(root, nodes);
return nodes;
}
private static void addAllDescendents(Parent parent, ArrayList<Node> nodes) {
for (Node node : parent.getChildrenUnmodifiable()) {
nodes.add(node);
if (node instanceof Parent)
addAllDescendents((Parent)node, nodes);
}
}
这篇关于如何在JavaFX中获得父节点中的所有节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!