JavaFX getChildren() List behaviour


Question

Look at the following code:

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());
    }

If the label gets added to group2 it automatically gets removed from group1. Does anyone know why this is intended?

Until now, I do not need the extra functionality e.g. bounds from the group class and use a simple ArrayList to store the references to the label objects.

1
2
11/26/2012 3:21:36 PM

From the 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.

When a Node is added to a Scene, the JavaFX system sets and manages attributes specific to that node at that location in the Scene Graph. One example is the location of the node as determined by a parent layout manager and it's constraints. Another is the css style set inherited from parent nodes. Both of these kinds of data may vary depending on the Node's location in the Scene Graph.

If the system allowed you to also place the same Node at another location in the Scene Graph, it would overwrite system calculated attributes determined for the first location. Everything would become very confused - resulting in programs that are difficult to reason about and possessing subtle bugs.

5
11/27/2012 8:49:24 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon