问题描述
我如何可以访问阶段,尤其是Flash影片的宽度和鼠标的位置从自定义类?
How can I access the stage and especially the width and mouse position of the flash Movie from a custom class?
package classes
{
import flash.events.*;
import flash.display.*;
public class TableManager extends Sprite
{
public function TableManager() {
sayStage();
}
public function sayStage():void
{
trace(stage);
}
}
}
这将只返回nill。我知道的DisplayObject没有任何阶段,直到他们已经启动,所以你不能访问舞台在构造函数,但即使我打电话sayStage()以后作为一个实例方法是行不通的。
This will only return nill. I know that DisplayObjects don't have any stage until they have been initiated so you can't access the stage in your constructor but even if I call sayStage() later as an instance method it won't work.
我是什么做错了吗?
推荐答案
如果TableManager是在舞台上,你可以访问舞台与 this.stage
。
If TableManager is on the stage you can access the stage with this.stage
.
诀窍是,你必须等待实例被添加到舞台上。你可以听的 ADDED_TO_STAGE
事件,所以你知道什么时候发生的事情。
The trick is you have to wait for the instance to be added to the stage. You can listen for the ADDED_TO_STAGE
event so you know when that's happened.
package classes {
import flash.events.*;
import flash.display.*;
public class TableManager extends Sprite {
public function TableManager() {
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);
}
}
}
这篇关于AS3不能从自定义类访问舞台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!