You
can add an object to a DisplayObjectContainer object by calling
the container’s
addChild()
or
addChildAt()
method.
In the case of the Stage, you can also add an object to its display
list during authoring by creating it, or in the case of components,
by dragging it to the Stage from the Components panel. To add an
object to a container with ActionScript, first create an instance
of it by invoking its constructor with the
new
operator
and then call the
addChild()
or
addChildAt()
method
to place it on the Stage and in the display list. The
addChild()
method
places the object at the next position in the display list, while
addChildAt()
specifies
the position at which to add the object. If you specify a position
that is already occupied, the object at that position, and those at
higher positions, move up by 1. The
numChildren
property
of a DisplayObjectContainer object contains the number of display
objects that it contains. You can retrieve an object from the display
list by calling the
getChildAt()
method and specifying
the position, or if you know the name of the object, by calling
the
getChildByName()
method.
Note:
When you add a component with ActionScript,
you must assign a name to it’s name property if you want to access
it by name in the display list.
The following example displays the names and positions of three
components in the display list. First, drag a NumericStepper, a
Button, and a ComboBox to the Stage so that they overlap each other
and give them instance names of
aNs
,
aButton
, and
aCb
.
Then add the following code to the Actions panel on Frame 1 of the
Timeline:
var i:int = 0;
while(i < numChildren) {
trace(getChildAt(i).name + " is at position: " + i++);
}
You should see the following lines in the Output panel:
aNs is at position: 0
aButton is at position: 1
aCb is at position: 2