gpt4 book ai didi

list - JavaFX getChildren() 列表行为

转载 作者:行者123 更新时间:2023-12-02 05:23:02 27 4
gpt4 key购买 nike

看下面的代码:

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.

Node 添加到 Scene 时,JavaFX 系统会在场景图中的那个位置设置和管理特定于该节点的属性。一个示例是由父布局管理器及其约束确定的节点位置。另一种是从父节点继承的css样式集。这两种数据都可能因节点在场景图中的位置而异。

如果系统允许您也将同一节点放置在场景图中的另一个位置,它将覆盖为第一个位置确定的系统计算属性。一切都会变得非常困惑 - 导致程序难以推理并具有细微的错误。

关于list - JavaFX getChildren() 列表行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13567802/

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