尝试使用stage.height放置图形时出错

时间:2009-11-16 22:31:29

标签: flash actionscript-3 null stage

嘿peepz!我有这个页脚图像,我想对齐到舞台的底部,但是我遇到了错误。

如您所见,我在构造函数中有一个ADDED_TO_STAGE侦听器。

package src.display{

import flash.text.*;
import flash.display.*;
import flash.geom.Matrix;
import flash.events.Event;

public class Frame extends Sprite {
    private var footer:Sprite = new Sprite();

    // ☼ ------ Constructor
    public function Frame():void {
        this.addEventListener(Event.ADDED_TO_STAGE, tracer);
    }

    public function tracer(event:Event) {
        trace("Frame added to stage --- √"+"\r");
        this.removeEventListener(Event.ADDED_TO_STAGE, tracer);
    }

    // ☼ ------ Init
    public function init():void {
        footer.graphics.beginFill(0x000);
        footer.graphics.drawRect(0,0,800,56);
        footer.graphics.endFill();
        footer.y = (stage.height - footer.height); // <-- This Line

        addChild(footer);
    }

}

}

如果我注释第26行(但当然我不希望Y为0),电影将正常工作:

footer.y = (stage.height - footer.height);

以下是我收到的输出窗口中的错误:

TypeError:错误#1009:无法访问空对象引用的属性或方法。     在src.display :: Frame / init()[/ Users / lgaban / Projects / Player / src / display / Frame.as:26]


更新

回答了我自己的问题,fix here

2 个答案:

答案 0 :(得分:1)

并非完全答案,但该错误告诉您该阶段为空。

答案 1 :(得分:1)

使用自定义事件有点矫枉过正,尤其是当您已将侦听器添加到舞台中时。我会这样做:

package src.display{

    import flash.text.*;
    import flash.display.*;
    import flash.geom.Matrix;
    import flash.events.Event;

    public class Frame extends Sprite {

        // don't instantiate your sprite here, it's weird! :)
        private var footer:Sprite;

        // this is the same as in your example
        public function Frame():void {
            this.addEventListener(Event.ADDED_TO_STAGE, handleAddedToStage);
        }

            // i renamed this to reflect what it does
        private function handleAddedToStage(event:Event) {
            trace("Frame added to stage --- √"+"\r");
            this.removeEventListener(Event.ADDED_TO_STAGE, handleAddedToStage);
            init();
        }

        // this is also essentially the same, except for private since it shouldn't be called from the outside
        private function init():void {
            footer = new Sprite();
            footer.graphics.beginFill(0x000);
            footer.graphics.drawRect(0,0,800,56);
            footer.graphics.endFill();
            footer.y = (stage.height - footer.height);

            addChild(footer);
        }

    }
}