Recipe 9.20.
Assigning Focus to a Text Field
Problem
You want to use ActionScript to bring focus to a
text field.
Solution
Use the Stage.focus property.
Discussion
Use the Stage.focus property to
programmatically assign focus to a specific text field. Every
display object has a stage property that references the
Stage instance. Therefore, from a class that extends a
display object class (Sprite, MovieClip, etc.) the
following code assigns focus to a text field called field:
stage.focus = field;
When an .swf first loads in a web
browser, it does not have focus. Therefore, you must move focus to
the Flash Player before you can programmatically assign focus to an
element of the Flash application. The following is a working
example that uses a sprite button to assign focus to a text
field:
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.events.MouseEvent;
public class TextExample extends Sprite {
public function TextExample( ) {
var field:TextField = new TextField( );
field.border = true;
field.background = true;
field.type = TextFieldType.INPUT;
addChild(field);
var button:Sprite = new Sprite( );
button.graphics.lineStyle( );
button.graphics.beginFill(0xFFFFFF);
button.graphics.drawRect(0, 0, 100, 50);
button.graphics.endFill( );
button.addEventListener(MouseEvent.CLICK, onClick);
button.y = 100;
addChild(button);
}
private function onClick(event:MouseEvent):void {
stage.focus = TextField(getChildAt(0));
}
}
}
To remove focus from a text field you should
assign Stage.focus the null value:
stage.focus = null;
|