将Loader添加到舞台上

时间:2013-03-21 00:34:53

标签: actionscript-3 actionscript flash-cs4

我的班级似乎无法进入舞台......几乎就像它不想被触及一样。我不知道出了什么问题。这是我现在拥有的课程:

package {

import flash.events.*;
import flash.display.*;
import flash.net.*;

public class gallery extends Sprite{

    private var imgPath:String = 'images/';
    private var imgCurrent:int = 0;
    private var images:Array = new Array();
    private var iLoader:Loader;

    function gallery()
    {
        this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
    }

    private function onAddedToStage(e:Event):void {
        this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
        sayStage();
    }

    public function sayStage():void {
        trace(this.stage);
    }

    public function setImgs(val:Array):void
    {
        for (var index:String in val){
            images[index] = val[index];
        }
    }

    public function getImgs():void
    {
        for (var index:String in images){
            trace(index + ':' + images[index] + ';');
        }
    }

    public function loadImg():void{

        iLoader = new Loader();
        iLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgressStatus);
        iLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaderReady);

        var fileRequest:URLRequest = new URLRequest(imgPath+'testimg.JPG');
        iLoader.load(fileRequest);

    }

    public function onProgressStatus(e:ProgressEvent) {   
        trace(e.bytesLoaded, e.bytesTotal); 
    }

    public function onLoaderReady(e:Event) {     
        stage.addChild(iLoader); // error!
    }

    public function updateImgCurrent(val:int):void
    {
        imgCurrent = imgCurrent + val;
    }

    public function getImgCurrent():int
    {
        return(imgCurrent);
    }

}

}

这就是我在swf文件中所做的事情:

var gal:gallery = new gallery();
var imagesGallery:Array = new Array();
imagesGallery.push('testimg.JPG');
imagesGallery.push('img2.JPG');
imagesGallery.push('img3.JPG');
gal.setImgs(imagesGallery);
gal.loadImg();

问题是在舞台上添加了iLoader。当我这样做时,我收到错误:

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at gallery/onLoaderReady()

为什么我不能访问舞台?或者我想要实现的是完全错误的,我应该以另一种方式看待舞台吗?我真的希望你能提前帮助我和许多人! :)

1 个答案:

答案 0 :(得分:2)

如果显示对象未添加到显示列表,则其stage属性设置为null (source)。 将其添加到显示列表后,它将被设置为对舞台对象的引用 试试这个:

var gal:gallery = new gallery();
addChild(gal); // this will trigger ADDED_TO_STAGE event and initialize stage property
var imagesGallery:Array = new Array();
imagesGallery.push('testimg.JPG');
imagesGallery.push('img2.JPG');
imagesGallery.push('img3.JPG');
gal.setImgs(imagesGallery);
gal.loadImg();