AS3.0 键盘事件

1,问题: 在开发应用中,需要对键盘事件做监听,但是要根据 focus 焦点 不同而 是否需要做反应。例如当焦点在 场景地图 上,这时候的快捷键 起作用 ,而打开一个应用程序后例如聊天框,聊天这时候 虽然也是键盘 事件 但我们不希望触发执行快捷键判断 之类的 。

键盘事件的监听 是要对stage做监听,那么当上述聊天情况发生时,聊天应用存在于stage中,不可避免的触发判断。

如源代码:

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler,false,0,true);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler,false,0,true);


只要稍改一下 转移 [color=red]stage[/color] 把键盘事件的监听具体到某个对象上, 就不同了,这就需要将舞台焦点设置到该对象上,方法如下:
stage.focus = child;  // child 是注册键盘事件的对象

测试代码如下:
package {
import flash.display.Sprite;
import flash.events.*;

import org.aswing.ASColor;
import org.aswing.AsWingManager;
import org.aswing.AssetPane;
import org.aswing.BorderLayout;
import org.aswing.GridLayout;
import org.aswing.JFrame;
import org.aswing.JLabel;
import org.aswing.JLoadPane;
import org.aswing.JPanel;
import org.aswing.border.LineBorder;

public class KeyboardEventExample extends Sprite {
private var bgColor:uint = 0x00CCFF;
private var size:uint = 80;


public function KeyboardEventExample() {
var child:Sprite = new Sprite();
child.graphics.beginFill(bgColor);
child.graphics.drawRect(0, 0, size, size);
child.graphics.endFill();
addChild(child);

stage.focus = child; // 设置焦点后,方可注册键盘事件

child.addEventListener(MouseEvent.CLICK,__setFoucs);
child.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
child.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);

initAswing();
}
private function initAswing():void {
AsWingManager.initAsStandard(this);
var jf:JFrame = new JFrame();
var pane:JPanel = new JPanel(new BorderLayout());
var centerPane:JPanel = new JPanel(new GridLayout(6,12,1,1));
pane.append(centerPane,BorderLayout.CENTER);
pane.append(new JLabel("test"),BorderLayout.SOUTH);
jf.setContentPane(pane);
jf.setLocationXY(100,200);
jf.setSizeWH(400,300);
jf.show();
}
private function __setFoucs(e:MouseEvent):void{
var child:Sprite = e.currentTarget as Sprite;
stage.focus =child;
//child.graphics.beginFill(bgColor);
child.graphics.lineStyle(2,0xffbbf0,1);
child.graphics.drawRect(0, 0, size, size);
}
private function keyDownHandler(event:KeyboardEvent):void {
trace("keyDownHandler: " + event.keyCode);
trace("ctrlKey: " + event.ctrlKey);
trace("keyLocation: " + event.keyLocation);
trace("shiftKey: " + event.shiftKey);
trace("altKey: " + event.altKey);
}

private function keyUpHandler(event:KeyboardEvent):void {
trace("keyUpHandler: " + event.keyCode);
}
}
}

你可能感兴趣的:(Flash,ActionScript)