在AS3中使用键盘单击按钮

时间:2013-08-30 14:14:02

标签: actionscript-3 flash-cs6

我正在尝试通过使用键盘上的“A”键单击按钮来执行此操作。我为这个按钮创建了两个框架但代码不起作用,尽管没有错误。

我是否需要在主班上放任何东西?任何人都可以帮忙解决这个问题吗?

package  {

    import flash.display.MovieClip;
    import flash.events.MouseEvent;
    import flash.display.Sprite;
    import flash.display.Stage;
    import flash.events.Event;
    import flash.events.KeyboardEvent;
    import flash.ui.Keyboard;

    public class controlButton extends MovieClip {      

        public function controlButton() {
            // constructor code
            this.addEventListener(KeyboardEvent.KEY_DOWN,clickDown);
            this.addEventListener(KeyboardEvent.KEY_UP,clickUp);
        }

        public function clickDown(event:KeyboardEvent):void{

         // if the key is A
            if(event.charCode == 65){
                this.gotoAndStop(2);
            }
        }

        public function clickUp(event:KeyboardEvent):void{

         // if the key is A
            if(event.charCode == 65){
                this.gotoAndStop(1);
            }
        }

        public function changelabel(newLabel:String):void{

            this.label.text = newLabel;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您的按钮永远不会收到任何 KeyboardEvent 。您应该将事件侦听器直接添加到舞台上。当然,您必须获得舞台的链接。反正:

package {

import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;


public class controlButton extends MovieClip {


    public function controlButton() {
        // constructor code
        addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
    }

    private function onAddedToStage (e:Event):void
    {
        removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
                    //stage is no longer null here
        stage.addEventListener(KeyboardEvent.KEY_DOWN,clickDown);
        stage.addEventListener(KeyboardEvent.KEY_UP,clickUp);
    }


    public function clickDown(event:KeyboardEvent):void{

     // if the key is A
         if(event.charCode == 65){
            this.gotoAndStop(2);
        } 


    }

    public function clickUp(event:KeyboardEvent):void{

     // if the key is A
         if(event.charCode == 65){
                this.gotoAndStop(1);
             }
    }



    public function changelabel(newLabel:String):void{

        this.label.text = newLabel;
    }
}

}

如您所见,您应该在Event.ADDED_TO_STAGE触发后立即将KeyboardEvent侦听器添加到舞台。