Note that there are some explanatory texts on larger screens.

plurals
  1. POActionScript: How to instantiate a Sprite subclass that adds itself to the stage?
    primarykey
    data
    text
    <p>I've created a wrapper around Sprite called ClickableCircle, which is meant to add itself to the display list when instantiated. Here's a toy version:</p> <pre><code>public class ClickableCircle extends Sprite { protected var circle:Shape; protected var myName:String; public function ClickableCircle(name:String, x:uint, y:uint) { super(); circle:Shape = new Shape(); circle.graphics.beginFill(0x00ACDC, 1); circle.graphics.drawCircle(0, 0, 12); this.myName = name; this.x = x; this.y = y; this.addChild(circle); this.addEventListener(MouseEvent.CLICK, reportClickedID); // Here's the problematic line: can't add itself to display list // Error #1009: Cannot access a property or method of a null object reference. stage.addChild(this); trace("Created " + name + " at " + String(x) + ", " + String(y)); } private function reportClickedID(e:MouseEvent):void { trace("You just clicked on " + this.myName); } } </code></pre> <p>The problem is that when a ClickableCircle is instantiated from the main application, it crashes when it tries to add itself to the stage, bc stage is null. If, on the other hand, the addChild() is commented out from the ClickableCircle constructor, and the instantiated cs is instead added to the display list at the main application level, everything works fine:</p> <pre><code>public class GreetingApp extends Sprite { public function GreetingApp() { var cs:ClickableCircle = new ClickableCircle("joe", 100, 200); // If the child is added here, everything works. stage.addChild(cs); } } </code></pre> <p>Since both GreetingApp and ClickableCircle extend Sprite, I would think the stage would be instantiated and accessible in both places. I'm brand new to ActionScript/Flex, so I'm sure I'm doing something stupid. Can anyone tell me what it is?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload