I'm currently getting started with javafx 8 and came up with the following problem in a simple solution:
I've different controls (Button
), which shall appear
- In the main content (center of a
Pane
) - In a footer (bottom of a
Pane
)
Button one = new Button("1");
Button two = new Button("2");
Button three = new Button("3");
VBox vbox = new VBox();
vbox.getChildren().addAll(one, two, three);
HBox hbox = new HBox();
hbox.getChildren().addAll(two, three); //To clarify my problem i leave one node in vbox
Now it appears to happen that the last .addAll()
, deletes the references in the other box.
BorderPane root = new BorderPane();
root.setCenter(vbox);
root.setBottom(hbox);
Output:
I tried (for testing) to simply reuse a button, but:
root.setCenter(one);
root.setBottom(one);
results in
java.lang.reflect.InvocationTargetException
...
Caused by: java.lang.RuntimeException: Exception in Application start method
...
Caused by: java.lang.IllegalArgumentException: Children: duplicate children added: parent = BorderPane@1784a61
That made me think about the following questions:
- Is there a way to work around that problem, except creating new button instances?
- What happens to the
HBox
andVBox
nodes? - Why controls can't be reused?
As said in the JavaDocs of the
Node
class:Therefore, you can't do what you're trying to do. One button can only be shown once, you can't have the same button at two places. To make this more clear - what should e.g. the
getParent()
method return if you were able to have the same instance at two places? Nothing, it's impossible. One instance can only exist at one place.You must copy the button if you want to reuse it.
The error you are getting
and that the scene shows the
"one" button
in the vbox and"two"
and"three"
in the hbox, is related. You declared only 3 buttons and the scene can only show 3 buttons. As per my comment, you need to declare button four and five and add those to the hbox and probably you will get to see all 5 buttons.I don't know exactly why it does it like that, but it has to do with the initialization of the controls. The result could also have been that it added 3 buttons to the vbox and none to the hbox. But because the hbox is initialized after the vbox, is why it puts button 2 and 3 in the vbox and discards them in the hbox.( or actually throws an exception)
In JavaFX nodes can only be used one time in the scene graph. This makes sence because a node, e.g., contains a location. If you would use it twice you would need two locations.