PDA

View Full Version : [AS3] keyboard event wont work :(


mad_man
11-26-2006, 10:05 PM
I decided to pick up a copy of O'reilly Actionscript 3 Cookbook today, and I have been going through. One of the first examples it has for keyboard events is:


package {
import flash.display.Sprite;
import flash.events.KeyboardEvent;

public class ExampleApplication extends Sprite {
public function ExampleApplication( ) {
stage.focus = this;
addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
}

private function onKeyDown(event:KeyboardEvent):void {
trace("key down: " + event.charCode);
}
}
}


But for some reason it will not work. According to the book stage.focus = this; is all you need for keyboard events to work, am i doing something wrong?

TheCanadian
11-26-2006, 10:28 PM
I assume you made it the doucment class since you didn't get any errors. When you test the movie you cannot click anywhere.

mad_man
11-26-2006, 10:43 PM
a document class?
well i followed the book, where i created an Actionscript Project and this is the .as file that is automatically created with it.

TheCanadian
11-26-2006, 10:50 PM
Well how do you create an instance of the class?

mad_man
11-26-2006, 10:59 PM
i dont, it automaticly calls the constructor.

TheCanadian
11-26-2006, 11:03 PM
What's it?

cocacoka
11-27-2006, 06:27 AM
same problem as mine

it is because the application is not yet created when the custom component is created. so your this.stage don't work (or simple infinite looping), you can try and put a trace() after the this.stage statement and test.

and yes. I dun have solution except putting a application complete event listener in application side and call the custom component to stage.focus.

agilius
11-27-2006, 09:45 AM
Try to put the code of the Constructor into a function that is called at ENTER_FRAME event. I think that should do the work. ;) I had the same problem 2 days ago but I fixed it like this.. I think.. I don remember exactly but its something about callling the function where the KeyEventListener is placed AFTER the appliction starts.

mad_man
11-27-2006, 05:57 PM
thanks for the help guys