AS3 Sprite added to Stage but not visible

I'm trying to get a simple AS3 app up and running, and for some reason, I cannot get a sprite to show. At this point, all I want to do is get a red sprite to fill the stage.

public class Main extends Sprite 
{       
    public function Main():void 
    {
        super();

        stage.scaleMode = StageScaleMode.NO_SCALE;
        stage.align = StageAlign.TOP_LEFT;

        var square:Sprite = new Sprite();   

        square.width = stage.stageWidth;
        square.height = stage.stageHeight;
        square.x = square.width / 2;
        square.y = square.height / 2;

        square.graphics.clear();
        square.graphics.lineStyle(3, 0xFF0000);
        square.graphics.beginFill(0xFF0000);
        square.graphics.drawRect(0, 0, width, height);
        square.graphics.endFill();

        square.addEventListener(Event.ADDED_TO_STAGE, addedToStage);
        square.addEventListener(MouseEvent.CLICK, onClick);

        addChild(square);
     }

     private function addedToStage(e:Event):void 
     {
          trace("Added sprite to stage");           
     }
     private function onClick(e:Event):void 
     {
          trace("Got click on sprite");         
     }      
}

The trace shows that the sprite was added to the stage, but nothing is displayed, and if I click on it, the onClick function never gets called. If I use a TextField instead of a Sprite, it displays just fine. There must be something weird about Sprites.

What am I doing wrong?

Thanks!

Answers


Trying to set the width and height for a empty Sprite will return 0. Have a look at here.

and

Refer Mr.Marty Wallace's answer.


Your issue is here:

square.graphics.drawRect(0, 0, width, height);

The values for width and height in this line are 0. The reason being that they are referring to the width and height properties of the class you're working within (Main - properties inherited from DisplayObject) which will be zero based on what I can see.

You're essentially saying:

square.graphics.drawRect(0, 0, 0, 0);

Which will render nothing.


Need Your Help

Cannot manually load xib from a view controller?

iphone objective-c ios xib nsbundle

I'm making an app using the Blackboard SDK. It would really help if you could download the SDK and see if you have the same errors.

How to set up Dreamweaver to use CodeIgniter?

codeigniter dreamweaver

I am using dreamweaver cs5 and xampp. I created a folder name CI in htdoc, where all my codeigniter files and folders are , i.e application, system , user_guide, license.txt, index.php and