Dynamically Add Components to a Container

There are many reasons why you might want to add components to containers dynamically. The most common reasons are for performance or flexibility. Either way, having a good understanding of how it works is essential.

First a little background information about what these methods are from
The addChild and addChildAt methods come from the DisplayObjectContainer class. The DisplayObjectContainer class is an abstract base class for all objects that can contain child objects. Being an abstract class means that It cannot be instantiated directly. You instantiate a class that implements it, such as Sprite or UIComponent.

DisplayObjectContainer is the base class for all objects that can serve as display object containers on the display list. The display list manages all objects displayed in Flash Player. Use the DisplayObjectContainer class to arrange the display objects in the display list. Each DisplayObjectContainer object has its own child list for organizing the z-order of the objects. The z-order is the front-to-back order that determines which object is drawn in front, which is behind, and so on.

How to do it:

  1. Instantiate a component that inherits the methods from DisplayObjectContainer.
  2. Create a method that will instantiate an object to be added.
  3. Set all of the properties to that object and then pass it to the addItem method
<?xml version=”1.0″?>
<!– Simple example to demonstrate the SWFLoader control. –>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” creationComplete=”init();”>

public function init():void
var circle1:Sprite = new Sprite();
circle1.graphics.beginFill( 0xFFCC00 );
circle1.graphics.drawCircle( 40, 40, 40 );
circle1.x = 30;
circle1.y = 30;
myLoader.addChild( circle1 );

<mx:Panel title=”SWFLoader Control Example” height=”90%” width=”90%”
paddingTop=”10″ paddingBottom=”10″ paddingLeft=”10″ paddingRight=”10″>

<mx:Label text=”The Label control of the outer application.”/>

<mx:SWFLoader id=”myLoader” height=”50″ width=”350″ click=”myLoader.visible=false”/>


In this simple example, I load another swf (not supplied) using the SWFLoader. Upon creationComplete of the application I add a Sprite to the SWFLoader. Note that I also set the x&y position so that both the loaded swf and the Sprite are not at the origin of the SWFLoader.

You can easily substitute the addItem with addItemAt by adding a level argument to the method call. This will determine which item is on top of the other.

myLoader.addChildAt( circle1, 0 );

So there you have it.