Trouble managing events in Flex/actionscript
I'm doing some newbie tests, so I decided to capture the keyboard events to move a rectangle. But I don't get the desired result. Unless I click on the TextArea box, I'm not able to capture the event key code. After that, all goes pretty well.
I'm using Eclipse 3.3 + Flex 3.0 on Linux.
Here's my code:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute"
enterFrame="enterFrame(event)"
keyDown="onKeyDown(event)">
<mx:TextArea id="myText" x="200" y="200" width="100" height="100" />
<mx:Canvas id="myCanvas" x="0" y="0" width="100" height="100" />
<mx:Script>
<![CDATA[
public var clearColor : uint = 0xFF456798;
public var myPoint : Point = new Point(0,0);
public function enterFrame(event:Event):void
{
myCanvas.graphics.clear();
myCanvas.graphics.beginFill(0xFF344ff0);
myCanvas.graphics.drawRect(myPoint.x,myPoint.y,40,40);
myCanvas.graphics.endFill();
}
public function onKeyDown(event:KeyboardEvent):void
{
myText.text = "Keycode is: " + event.keyCode + "\n";
switch(event.keyCode)
{
case 37: //Left
myPoint.x -= 1;
break;
case 38: //Up
开发者_如何学运维 myPoint.y -= 1;
break;
case 39: //Right
myPoint.x += 1;
break;
case 40: //Down
myPoint.y += 1;
break;
}
}
]]>
</mx:Script>
</mx:Application>
Keyboard events are only dispatched to the DisplayObject with the current focus and all its parents. Most reliable way to get a KeyboardEvent is to register the handler to the stage. However handling KeyboardEvents unaware of focus or any other form of context usually leads to strange behaviour, so you will have to put some thought into it.
greetz
back2dos
精彩评论