如何在actionscript中为一个特定按钮添加keyBoardEvent?

时间:2014-05-02 16:03:47

标签: actionscript-3 flash flex actionscript flash-builder

我是动作脚本的新手。刚开始学习它几天前。我正在尝试为特定按钮添加keyboardevents。这是我到目前为止所做的。

import flash.events.KeyboardEvent;
public function f1():void
{
     // something
}
public function keyBoardListener(keyEvent:KeyboardEvent):void
{
    if(keyEvent.keyCode==37)
        f1();

}

并按下按钮

<Lib:ManagedButton
     id = "MB"
     labelText = "MB"
     image = " ... "
     click="f1()"
     enabled = "false"
     stage.addEventListener(KeyboardEvent.KEY_DOWN,keyBoardListener);
 />

这是我得到的错误:

Attribute name "stage.addEventListener" associated with an element type "Lib:ManagedButton" must be followed by the ' = ' character.    

我要做的是按左箭头键调用函数f1()。我不希望这个页面上的所有按钮都发生这种情况,只有这个按钮。

1 个答案:

答案 0 :(得分:3)

您的问题如下:

stage.addEventListener(KeyboardEvent.KEY_DOWN,keyBoardListener);

您在标记中将其作为属性(它期望 param =“value”)并且您尝试调用代码函数。

您应该为按钮创建一个类文件,并在那里添加监听器和处理程序。这样它只会在按钮具有焦点时运行(这是我假设你想要的)。

package Lib {
    public class MyButton extends ManagedButton {
        public function MyButton(){
            this.addEventListener(Event.ADDED_TO_STAGE,addedToStage,false,0,true);
            this.addEventListener(Event.REMOVED_FROM_STAGE,removedFromStage,false,0,true);
            this.addEventListener(MouseEvent.CLICK,clickEventHandler,false,0,true);
        }

        private function addedToStage(e:Event):void {
            this.addEventListener(KeyboardEvent.KEY_DOWN, keyBoardListener,false,0,true);
        }
        private function removedFromStage(e:Event):void {
            this.removeEventListener(KeyboardEvent.KEY_DOWN, keyBoardListener,false);
        }

        [Bindable]
        public var clickHandler:Function;

        private function clickEventHandler(e:Event):void {
            if(clickHandler != null) clickHandler();
        }
        public function keyBoardListener(keyEvent:KeyboardEvent):void
        {
            if(keyEvent.keyCode==37)
               if(clickHandler != null) clickHandler();
        }
    }
}

然后你可以指定clickHandler的值,并让你的键盘和点击事件启动它。我没有真正使用FLEX,所以有人可能需要纠正这个问题,但我认为这就是它的样子:

<Lib:MyButton
     id = "MB"
     labelText = "MB"
     image = " ... "
     enabled = "false"
     clickHandler = "f1()"
 />