This code is in Gwt but if u just know Java then u still can be able to answer this question.
Ok, i have 2 panels: myPanel1 & myPanel2, then I add myPanel2 into myPanel1 many times
myPanel1.add(myPanel2);
myPanel1.add(myPanel2);
myPanel1.add(myPanel2);
myPanel1.add(myPanel2);
....
Then I count the number of Widgets in myPanel1
System.out.println("No of Widgets inside myPanel1: "+ myPanel1.getWidgetCount());
The result is "No of Widgets inside myPanel1: 1
"
Why number of Widgets inside myPanel1 is still 1 even though we added myPanel2 into myPanel1 many times?
I'm not a GWT developer, but I suspect this is calling Panel.add(Widget)
which documents these steps (emphasis mine):
There are several important things that must take place in the correct order to properly add or insert a Widget to a Panel. Not all of these steps will be relevant to every Panel, but all of the steps must be considered.
- Validate: Perform any sanity checks to ensure the Panel can accept a new Widget. Examples: checking for a valid index on insertion; checking that the Panel is not full if there is a max capacity.
- Adjust for Reinsertion: Some Panels need to handle the case where the Widget is already a child of this Panel. Example: when performing a reinsert, the index might need to be adjusted to account for the Widget's removal. See ComplexPanel.adjustIndex(Widget, int).
- Detach Child: Remove the Widget from its existing parent, if any. Most Panels will simply call Widget.removeFromParent() on the Widget.
- Logical Attach: Any state variables of the Panel should be updated to reflect the addition of the new Widget. Example: the Widget is added to the Panel's WidgetCollection at the appropriate index.
- Physical Attach: The Widget's Element must be physically attached to the Panel's Element, either directly or indirectly.
- Adopt: Call adopt(Widget) to finalize the add as the very last step.
In other words, when you add something to one panel, it's removed from whatever panel it's currently part of, if any.
To be honest, it's not clear what effect you expected anyway - you've still only got two objects... what would it mean for a single widget to be in a panel multiple times? If you want multiple widgets, create multiple objects.
See more on this question at Stackoverflow