Reputation: 1050
I have observed some weird behavior while dealing with some java fx components. I am trying to dynamically add children to a parent node via the controller, once a button is pressed on the GUI. Here is a reproducible scenario of the problem:
VBox vbox = new VBox();
HBox entry = new HBox();
Button button = new Button();
TextField text = new TextField();
entry.getChildren().add(text);
entry.getChildren().add(button);
vbox.getChildren().add(entry);
System.out.println(vbox.getChildren().isEmpty() ? "empty" : "not empty"); //prints out "not empty"
HBox newEntry = new HBox(entry);
System.out.println(vbox.getChildren().isEmpty() ? "empty" : "not empty"); //prints out "empty"
Can you please enlighten me why vbox
is losing entry
as a child when I pass entry
to a constructor? I am passing entry
to the constructor in order to copy all the other object attributes/properties that are already set via the FXML form. In my actual code, each element has a different identifier, set via the node.setId()
method, so duplicate IDs are not the problem. Am I not aware of some underlying mechanism? Thank you.
Upvotes: 0
Views: 310
Reputation: 82451
I am passing
entry
to the constructor in order to copy all the other object attributes/properties that are already set via the FXML form.
It doesn't work this way. That constructor adds the same instance as child of the newly created HBox
. Since a Node
can only have a single parent and a Node
occurs in the child list of it's Parent
, JavaFX has to fix the state by removing the Node
from the child list of it's former parent.
Note that quite a few Pane
s allow you to pass children to one of the constructor. Those are not copy constructors, but simply "shortcuts" for that allow you to add the children without using pane.getChildren().addAll(children);
In fact I'm not aware of any copy constructor for Node
s in the JavaFX API.
HBox newEntry = new HBox(entry);
Creates a new HBox
containing entry
as it's only child.
Instead of trying to copy a part of the scene graph, it's most often easier to create a helper method that creates the part of the scene graph (which can also be done using a fxml file).
(There is no functionality in the JavaFX API allowing you to create a copy of a Node
hierarchy.)
Upvotes: 3