views:

33

answers:

1

Hello all,

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>
+1  A: 

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

back2dos