list - JavaFX getChildren() 列表行为

标签 list parent javafx

看下面的代码:

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/

相关文章:

java - 按元素对列表项进行分组以在 jsp 收据中使用

python - 在嵌套列表中拆分字符串

python - 列表理解与生成器表达式的奇怪时间结果?

CSS 选择具有特定子元素的元素的兄弟?

JavaFX 滚动开始和结束

java - 使用第二行和第三行偏移制作矩形网格?

python - 在字典列表中查找最大长度的所有字典

Magento 如何从产品中获取子类别的父类别

javascript - Salesforce 页面弹出窗口使用另一个 URL 打开

JavaFX:公开 ObjectProperty 成员而不是 getter/setter?