计时器方法不会将文本字段添加到精灵

时间:2011-09-02 14:34:41

标签: actionscript-3 actionscript

当我按下键盘向下按钮时,文本字段将添加到精灵,但不会通过计时器事件调用。那是为什么?

package
{

    import flash.display.Sprite;
    import flash.events.KeyboardEvent;
    import flash.text.TextField;
    import flash.utils.Timer;
    import flash.events.TimerEvent;

    public class Test extends Sprite
    {

        public function Test()
        {
            var timer:Timer = new Timer(3);

            stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
            timer.addEventListener(TimerEvent.TIMER, onTime);
            timer.start();

        }

        function onKeyDown(event:KeyboardEvent):void {

            //          graphics.lineStyle(10,Math.random() * 10000, 10);
            //          graphics.drawCircle(100, 100, 80);  

            var txtFld:TextField = new TextField();

            txtFld.x = 200;
            txtFld.y = 200;
            txtFld.width = 25;
            txtFld.height = 15;
            txtFld.text = "90";         

            addChild(txtFld);
        }



        function onTime(event:Timer):void {


            var txtFld:TextField = new TextField();

            txtFld.x = 100;
            txtFld.y = 100;
            txtFld.width = 25;
            txtFld.height = 15;
            txtFld.text = "80";     

            addChild(txtFld);
        }

    }

}

1 个答案:

答案 0 :(得分:1)

在计时器事件处理程序中,您将传入的事件对象强制转换为Timer,而不是TimerEvent。这会导致Flash播放器抛出错误。

此外,此代码将继续添加TextFields,因为Timer正在循环并在每个循环上调用此函数。

function onTime(event:TimerEvent):void {
    //stop the timer
    evt.target.stop();

    var txtFld:TextField = new TextField();

    txtFld.x = 100;
    txtFld.y = 100;
    txtFld.width = 25;
    txtFld.height = 15;
    txtFld.text = "80";     

    addChild(txtFld);
}