Search code examples
actionscript-3flashstage

Line stage.addeventlistener gives error; How to instantiate stage?


I have a problem with the stage.addeventlistner. After doing some research i found some hints that it probably isn't instantiated.

How do I do that?

typeerror error #1009 cannot access a property or method of a null object reference

(the line it refers to is the stage.addeventlistener)

The code with only the important bits

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
  }
 }
}

Solution

  • You can use the ADDED_TO_STAGE event to trigger your init code :

    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);
    
    }