package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.events.MouseEvent;
public class SampleAdd extends Sprite {
public var star:Sprite = new Sprite ;
public function SampleAdd():void {
init();
}
private function init():void {
star.graphics.beginFill(0xfff00f);
star.graphics.drawRect(0,0,50,50);
star.graphics.endFill();
for (var i:int = 0; i < 4; i++) {
if (i < 2) {//创建2个方块容器,用来装star
var con:RectSprite = new RectSprite("",0xFFCC00);
con.name = "con" + i;
addChild(con);
con.y = con.height + 50 * i;
} else {//创建2个按钮,设置单击哪个对应将star添加到上面2个方块中的一个,由此证明了一个显示对象只能出现在一个容器中,不能同时出现在2个容器中
con = new RectSprite("",0xFFEE00);
con.name = "btn" + i;
//给按钮添加标签,方便看到名字
var _label:TextField = new TextField;
_label.text = "Button" + i;
con.addChild(_label);
addChild(con);
con.x = 50 + 50 * i;
con.addEventListener(MouseEvent.CLICK,onbtn);
}
}
}
private function onbtn(e:MouseEvent):void {
switch (e.currentTarget.name) {
case "btn2" :
(getChildByName("con0") as Sprite).addChild(star);
//注意:上面for循环里的con是临时变量,如果此处只写con0.addChild(star),将提示找不到con0,所以上面给con取名(唯一的ID号con.name),此处再通过getChildByName获取con0
break;
case "btn3" :
(getChildByName("con1") as Sprite).addChild(star);
break;
}
}
}
}