inicio mail me! sindicaci;ón

t-roy.net*

blog by designer troy ginbey

Adding & removing display objects from the display list in AS3.0

package {
import flash.display.*;
import flash.text.TextField;

public class AS3Tester extends Sprite {
public function AS3Tester() {
var myTextContainer:TextField = new TextField();
myTextContainer.text = "I like beer";
this.addChild(myTextContainer);
}
}
}

In the above code, I create a variable to reference a new TextField object, and set it’s text to “I like beer”. This alone wont add the TextField to the stage. To do this I then need to use the addChild method to add it to the display list:

addChild(child:DisplayObject):DisplayObject

addChild is a method of DisplayObjectContainer. When a DisplayObjectContainer (a Sprite, a Loader or the Stage) calls the addChild method, it adds a child DisplayObject instance to that DisplayObjectContainer instance.

To remove an object from the display list is the reverse:
removeChild(child:DisplayObject):DisplayObject

So the code to remove the TexField above would be:
this.removeChild(myTextContainer);

If I wanted to add a display object instance to a specific DisplayObjectContainer instance, I use addChildAt:
addChildAt(child:DisplayObject, index:int):DisplayObject

Here’s an example of the code in use:

var myDisplayContainer:Sprite = new Sprite();

var myFirstSprite:Sprite = new Sprite();
var mySecondSprite:Sprite = new Sprite();

myDisplayContainer.addChild(myFirstSprite);
myDisplayContainer.addChildAt(mySecondSprite, 0);

this.addChild(myDisplayContainer);

The above code first creates a DisplayObjectContainer called myDisplayContainer, then adds a Sprite (myFirstSprite) to it. Then using addChildAt, a second sprite is added to myDisplayContainer at index 0, which is the back of the list - meaning it will be displayed underneath myFirstSprite.

The final line adds the myDisplayContainer to the stage.

No comments yet »

Your comment

HTML-Tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>