I’m new to ActionScript development and am using the FlashDevelop IDE. I’ve been playing around with some really simplistic things and have come across a problem I can’t seem to solve.
My application compiles and runs, and a function that watches click events fires perfectly and I can see the event in the console when I pass it to trace(), yet the same code watching for KeyboardEvent fails to fire at all.
Here’s my code:
package GameTesting
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
[Frame(factoryClass="GameTesting.Preloader")]
public class Main extends Sprite
{
public function Main():void
{
if (stage) {
init();
} else {
addEventListener(Event.ADDED_TO_STAGE, init);
}
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE,init);
addEventListener(MouseEvent.CLICK, onClickEvent);
addEventListener(KeyboardEvent.KEY_DOWN, onKeyDownEvent);
}
private function onKeyDownEvent(e:KeyboardEvent):void
{
trace(e);
}
private function onClickEvent(e:MouseEvent):void
{
trace(e);
}
}
}
The MouseEvent trace() fires every time as expected, but KeyboardEvent never fires, no matter what key I press. Any ideas?
You need to add the listeners to the stage: