0

我试图通过使用键盘上的“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;
        }
    }
}
4

1 回答 1

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 侦听器添加到舞台。

于 2013-08-30T14:20:27.303 回答