line stage.addeventlistener给出错误;如何实例化阶段?

时间:2013-01-13 18:20:35

标签: actionscript-3 flash stage

我的stage.addeventlistner有问题。在做了一些研究后,我发现了一些暗示它可能没有实例化。

我该怎么做?

  

typeerror error#1009无法访问空对象引用的属性或方法

(它引用的行是stage.addeventlistener)

仅包含重要位的代码

package 
{
import flash.display.MovieClip;
import flash.events.*;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.geom.Point;

public class TesTrun extends MovieClip 
{
    var leftPressed:Boolean = false;
    var rightPressed:Boolean = false;
    var upPressed:Boolean = false;
    var downPressed:Boolean = false;
public function TestRun() 
    {    

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.addEventListener(Event.ENTER_FRAME, loop);
      //there is more code down here but i don't think that has to be included
  }
 }
}

1 个答案:

答案 0 :(得分:1)

您可以使用ADDED_TO_STAGE事件触发初始化代码:

public function TestRun() 
{    
    addEventListener(Event.ADDED_TO_STAGE, init);
}

public function init(e:Event):void
{
    stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
    stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
    stage.addEventListener(Event.ENTER_FRAME, loop);

}