看下面的代码:
public static void main(String[] args) {
Group group1 = new Group();
Group group2 = new Group();
Label label = new Label("test");
group1.getChildren().add(label);
group2.getChildren().add(label);
System.out.println("Size group1: " +group1.getChildren().size());
System.out.println("Size group2: " +group2.getChildren().size());
}
如果标签添加到 group2,它会自动从 group1 中删除。有谁知道为什么要这样做?
到目前为止,我不需要额外的功能,例如来自组类的边界,并使用简单的 ArrayList 来存储对标签对象的引用。
最佳答案
来自 Node
documentation :
A node may occur at most once anywhere in the scene graph. Specifically, a node must appear no more than once in all of the following: as the root node of a Scene, the children ObservableList of a Parent, or as the clip of a Node.
...
If a program adds a child node to a Parent (including Group, Region, etc) and that node is already a child of a different Parent or the root of a Scene, the node is automatically (and silently) removed from its former parent.
...
It is possible to rearrange the structure of the scene graph, for example, to move a subtree from one location in the scene graph to another. In order to do this, one would normally remove the subtree from its old location before inserting it at the new location. However, the subtree will be automatically removed as described above if the application doesn't explicitly remove it.
当将节点
添加到场景
时,JavaFX系统会在场景图中的该位置设置和管理特定于该节点的属性。一个示例是由父布局管理器及其约束确定的节点位置。另一个是从父节点继承的css样式集。这两种数据可能会根据节点在场景图中的位置而有所不同。
如果系统允许您将相同的节点放置在场景图中的另一个位置,它将覆盖为第一个位置确定的系统计算属性。一切都会变得非常困惑 - 导致程序难以推理并具有微妙的错误。
关于list - JavaFX getChildren() 列表行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13567802/