PDA

View Full Version : Class unable to access parent properties.


Ken Rogers
08-02-2008, 03:36 AM
I have created a program with an "Aircraft" class which has the child "Panel". Panel seems unable to access the variables of its' parent. I get the following error when I run my program:

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Panel$iinit()
at DataTag/::showPanel()

Here is my code:

package
{
import flash.display.*;
import flash.events.*;
import flash.text.TextField;

public class Panel extends MovieClip
{
var needle:Needle = new Needle();
public function Panel()
{
enterButton.addEventListener(MouseEvent.CLICK, closePanel);
addChild(needle);
needle.rotation = MovieClip(this.parent).heading;
}

function closePanel(event:MouseEvent):void
{
this.parent.removeChild(this);
}
}
}

How can Panel access the variables of its' parent?

bloodstyle
08-02-2008, 04:00 AM
You can, but only after you addChild an instance of Panel somewhere. Until you do that, it has no parent so it'll be null.

Ken Rogers
08-02-2008, 04:22 AM
In a separate class, "DataTag", an instance of Panel is added to the display list shown below:

package
{
import flash.display.*;
import flash.events.*;
import flash.text.TextField;

public class DataTag extends MovieClip
{
public var panel:Panel;

public function DataTag()
{
this.addEventListener(MouseEvent.CLICK, showPanel);

}

function showPanel(event:MouseEvent):void
{
panel = new Panel();
this.parent.addChild(panel);
panel.x = 74;
panel.y = 74;
}
}
}

Ken Rogers
08-03-2008, 03:26 AM
My DataTag class has added child, and my Panel class has casted the parent, but my Panel class cannot access variables that exist within its' parent.

bloodstyle
08-03-2008, 02:10 PM
You can't access parent variables in the constructor unless you pass them, you'll have to do it in a separate function(because it doesn't have a parent at the time the constructor code is executed). Or better yet, addChild it directly at its parent and just pass in the values you need, and let the parent take care of removing it as well.