Home >
If you ever build your own custom components that extend UIComponent, you'll no doubt run into this scenario... Even if you add event listeners for keyboard events, or if you override the keyDownHandler function, you may find that your keyboard events aren't being handled by your component instances. Setting focusEnabled, mouseFocusEnabled, or tabEnabled don't seem to do the trick either... Don't pull your hair out! It's an easy fix.
You may have noticed that if you extend a Canvas, a Button, or virtually any other Flex component (Spark or Halo), then you can accept keyboard events without any problems. However if you are building custom components, and you want an absolutely blank object (as bare-bones as you can get), then you want to extend UIComponent. UIComponent is the root of all visual Flex components, including all Halo and Spark component sets.
Enabling keyboard support within a UIComponent is as simple as implementing the "IFocusManagerComponent" interface. All the methods to fulfill the IFocusManagerComponent interface are already defined within the UIComponent base class, so literally all you need to do is add the "extends IFocusManagerComponent" to your class declaration.
Here's a quick example. It is a custom component that accepts keyboard input and displays it onscreen:
And here's the code to make the component work:
package
{
import flash.events.KeyboardEvent;
import mx.controls.Text;
import mx.core.UIComponent;
import mx.managers.IFocusManagerComponent;
public class UIComponentWithKeyboard
extends UIComponent
implements IFocusManagerComponent
{
private var txt : Text;
override protected function createChildren() : void
{
super.createChildren();
txt = new Text();
txt.visible = true;
txt.setStyle("color", 0);
txt.text = "click here, and press any key to accept keyboard events";
addChild( txt );
}
override protected function updateDisplayList(w:Number, h:Number) : void
{
super.updateDisplayList(w,h);
txt.width = w;
txt.height = h;
with (this.graphics)
{
clear();
beginFill(0xFF0000, .1);
drawRect(0,0,w,h);
}
}
override protected function keyDownHandler(event:KeyboardEvent) : void
{
txt.text = "keycode: " + event.keyCode +
", location: " + event.keyLocation +
", charcode: " + event.charCode +
", value: " + String.fromCharCode( event.charCode );
}
}
}
___________________________________
Andrew Trice
Principal Architect
Cynergy Systems
http://www.cynergysystems.com




Facebook Application Development
Comments
Leave a comment