Adobe® Flex® 4 Language Reference
Show Packages and Classes List |  Packages  |  Classes  |  Index  |  Appendixes
flash.text 
TextField 
Packageflash.text
Classpublic class TextField
InheritanceTextField Inheritance InteractiveObject Inheritance DisplayObject Inheritance EventDispatcher Inheritance Object
Subclasses FlexTextField

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

The TextField class is used to create display objects for text display and input. You can use the TextField class to perform low-level text rendering. However, in Flex, you typically use the Label, Text, TextArea, and TextInput controls to process text. You can give a text field an instance name in the Property inspector and use the methods and properties of the TextField class to manipulate it with ActionScript. TextField instance names are displayed in the Movie Explorer and in the Insert Target Path dialog box in the Actions panel.

To create a text field dynamically, use the TextField() constructor.

The methods of the TextField class let you set, select, and manipulate text in a dynamic or input text field that you create during authoring or at runtime.

ActionScript provides several ways to format your text at runtime. The TextFormat class lets you set character and paragraph formatting for TextField objects. You can apply Cascading Style Sheets (CSS) styles to text fields by using the TextField.styleSheet property and the StyleSheet class. You can use CSS to style built-in HTML tags, define new formatting tags, or apply styles. You can assign HTML formatted text, which optionally uses CSS styles, directly to a text field. HTML text that you assign to a text field can contain embedded media (movie clips, SWF files, GIF files, PNG files, and JPEG files). The text wraps around the embedded media in the same way that a web browser wraps text around media embedded in an HTML document.

Flash Player supports a subset of HTML tags that you can use to format text. See the list of supported HTML tags in the description of the htmlText property.

View the examples

See also



Public Properties
 PropertyDefined By
 InheritedaccessibilityImplementation : AccessibilityImplementation
The current accessibility implementation (AccessibilityImplementation) for this InteractiveObject instance.
InteractiveObject
 InheritedaccessibilityProperties : AccessibilityProperties
The current accessibility options for this display object.
DisplayObject
 Inheritedalpha : Number
Indicates the alpha transparency value of the object specified.
DisplayObject
  alwaysShowSelection : Boolean
When set to true and the text field is not in focus, Flash Player highlights the selection in the text field in gray.
TextField
  antiAliasType : String
The type of anti-aliasing used for this text field.
TextField
  autoSize : String
Controls automatic sizing and alignment of text fields.
TextField
  background : Boolean
Specifies whether the text field has a background fill.
TextField
  backgroundColor : uint
The color of the text field background.
TextField
 InheritedblendMode : String
A value from the BlendMode class that specifies which blend mode to use.
DisplayObject
 InheritedblendShader : Shader
[write-only] Sets a shader that is used for blending the foreground and background.
DisplayObject
  border : Boolean
Specifies whether the text field has a border.
TextField
  borderColor : uint
The color of the text field border.
TextField
  bottomScrollV : int
[read-only] An integer (1-based index) that indicates the bottommost line that is currently visible in the specified text field.
TextField
 InheritedcacheAsBitmap : Boolean
If set to true, Flash runtimes cache an internal bitmap representation of the display object.
DisplayObject
 InheritedAIR-only cacheAsBitmapMatrix : Matrix
If non-null, this Matrix object defines how a display object is rendered when cacheAsBitmap is set to true.
DisplayObject
  caretIndex : int
[read-only] The index of the insertion point (caret) position.
TextField
  condenseWhite : Boolean
A Boolean value that specifies whether extra white space (spaces, line breaks, and so on) in a text field with HTML text is removed.
TextField
 Inheritedconstructor : Object
A reference to the class object or constructor function for a given object instance.
Object
 InheritedcontextMenu : NativeMenu
Specifies the context menu associated with this object.
InteractiveObject
  defaultTextFormat : flash.text:TextFormat
Specifies the format applied to newly inserted text, such as text entered by a user or text inserted with the replaceSelectedText() method.
TextField
  displayAsPassword : Boolean
Specifies whether the text field is a password text field.
TextField
 InheriteddoubleClickEnabled : Boolean
Specifies whether the object receives doubleClick events.
InteractiveObject
  embedFonts : Boolean
Specifies whether to render by using embedded font outlines.
TextField
 Inheritedfilters : Array
An indexed array that contains each filter object currently associated with the display object.
DisplayObject
 InheritedfocusRect : Object
Specifies whether this object displays a focus rectangle.
InteractiveObject
  gridFitType : String
The type of grid fitting used for this text field.
TextField
 Inheritedheight : Number
Indicates the height of the display object, in pixels.
DisplayObject
  htmlText : String
Contains the HTML representation of the text field contents.
TextField
  length : int
[read-only] The number of characters in a text field.
TextField
 InheritedloaderInfo : LoaderInfo
[read-only] Returns a LoaderInfo object containing information about loading the file to which this display object belongs.
DisplayObject
 Inheritedmask : DisplayObject
The calling display object is masked by the specified mask object.
DisplayObject
  maxChars : int
The maximum number of characters that the text field can contain, as entered by a user.
TextField
  maxScrollH : int
[read-only] The maximum value of scrollH.
TextField
  maxScrollV : int
[read-only] The maximum value of scrollV.
TextField
 InheritedmouseEnabled : Boolean
Specifies whether this object receives mouse, or other user input, messages.
InteractiveObject
  mouseWheelEnabled : Boolean
A Boolean value that indicates whether Flash Player automatically scrolls multiline text fields when the user clicks a text field and rolls the mouse wheel.
TextField
 InheritedmouseX : Number
[read-only] Indicates the x coordinate of the mouse or user input device position, in pixels.
DisplayObject
 InheritedmouseY : Number
[read-only] Indicates the y coordinate of the mouse or user input device position, in pixels.
DisplayObject
  multiline : Boolean
Indicates whether field is a multiline text field.
TextField
 Inheritedname : String
Indicates the instance name of the DisplayObject.
DisplayObject
  numLines : int
[read-only] Defines the number of text lines in a multiline text field.
TextField
 InheritedopaqueBackground : Object
Specifies whether the display object is opaque with a certain background color.
DisplayObject
 Inheritedparent : DisplayObjectContainer
[read-only] Indicates the DisplayObjectContainer object that contains this display object.
DisplayObject
 Inheritedprototype : Object
[static] A reference to the prototype object of a class or function object.
Object
  restrict : String
Indicates the set of characters that a user can enter into the text field.
TextField
 Inheritedroot : DisplayObject
[read-only] For a display object in a loaded SWF file, the root property is the top-most display object in the portion of the display list's tree structure represented by that SWF file.
DisplayObject
 Inheritedrotation : Number
Indicates the rotation of the DisplayObject instance, in degrees, from its original orientation.
DisplayObject
 InheritedrotationX : Number
Indicates the x-axis rotation of the DisplayObject instance, in degrees, from its original orientation relative to the 3D parent container.
DisplayObject
 InheritedrotationY : Number
Indicates the y-axis rotation of the DisplayObject instance, in degrees, from its original orientation relative to the 3D parent container.
DisplayObject
 InheritedrotationZ : Number
Indicates the z-axis rotation of the DisplayObject instance, in degrees, from its original orientation relative to the 3D parent container.
DisplayObject
 Inheritedscale9Grid : Rectangle
The current scaling grid that is in effect.
DisplayObject
 InheritedscaleX : Number
Indicates the horizontal scale (percentage) of the object as applied from the registration point.
DisplayObject
 InheritedscaleY : Number
Indicates the vertical scale (percentage) of an object as applied from the registration point of the object.
DisplayObject
 InheritedscaleZ : Number
Indicates the depth scale (percentage) of an object as applied from the registration point of the object.
DisplayObject
  scrollH : int
The current horizontal scrolling position.
TextField
 InheritedscrollRect : Rectangle
The scroll rectangle bounds of the display object.
DisplayObject
  scrollV : int
The vertical position of text in a text field.
TextField
  selectable : Boolean
A Boolean value that indicates whether the text field is selectable.
TextField
  selectionBeginIndex : int
[read-only] The zero-based character index value of the first character in the current selection.
TextField
  selectionEndIndex : int
[read-only] The zero-based character index value of the last character in the current selection.
TextField
  sharpness : Number
The sharpness of the glyph edges in this text field.
TextField
 Inheritedstage : Stage
[read-only] The Stage of the display object.
DisplayObject
  styleSheet : StyleSheet
Attaches a style sheet to the text field.
TextField
 InheritedtabEnabled : Boolean
Specifies whether this object is in the tab order.
InteractiveObject
 InheritedtabIndex : int
Specifies the tab ordering of objects in a SWF file.
InteractiveObject
  text : String
A string that is the current text in the text field.
TextField
  textColor : uint
The color of the text in a text field, in hexadecimal format.
TextField
  textHeight : Number
[read-only] The height of the text in pixels.
TextField
  textWidth : Number
[read-only] The width of the text in pixels.
TextField
  thickness : Number
The thickness of the glyph edges in this text field.
TextField
 Inheritedtransform : flash.geom:Transform
An object with properties pertaining to a display object's matrix, color transform, and pixel bounds.
DisplayObject
  type : String
The type of the text field.
TextField
  useRichTextClipboard : Boolean
Specifies whether to copy and paste the text formatting along with the text.
TextField
 Inheritedvisible : Boolean
Whether or not the display object is visible.
DisplayObject
 Inheritedwidth : Number
Indicates the width of the display object, in pixels.
DisplayObject
  wordWrap : Boolean
A Boolean value that indicates whether the text field has word wrap.
TextField
 Inheritedx : Number
Indicates the x coordinate of the DisplayObject instance relative to the local coordinates of the parent DisplayObjectContainer.
DisplayObject
 Inheritedy : Number
Indicates the y coordinate of the DisplayObject instance relative to the local coordinates of the parent DisplayObjectContainer.
DisplayObject
 Inheritedz : Number
Indicates the z coordinate position along the z-axis of the DisplayObject instance relative to the 3D parent container.
DisplayObject
Public Methods
 MethodDefined By
  
Creates a new TextField instance.
TextField
 Inherited
addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event.
EventDispatcher
  
Appends the string specified by the newText parameter to the end of the text of the text field.
TextField
 Inherited
Dispatches an event into the event flow.
EventDispatcher
 Inherited
getBounds(targetCoordinateSpace:DisplayObject):Rectangle
Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object.
DisplayObject
  
Returns a rectangle that is the bounding box of the character.
TextField
  
Returns the zero-based index value of the character at the point specified by the x and y parameters.
TextField
  
Given a character index, returns the index of the first character in the same paragraph.
TextField
  
Returns a DisplayObject reference for the given id, for an image or SWF file that has been added to an HTML-formatted text field by using an <img> tag.
TextField
  
Returns the zero-based index value of the line at the point specified by the x and y parameters.
TextField
  
Returns the zero-based index value of the line containing the character specified by the charIndex parameter.
TextField
  
getLineLength(lineIndex:int):int
Returns the number of characters in a specific text line.
TextField
  
Returns metrics information about a given text line.
TextField
  
getLineOffset(lineIndex:int):int
Returns the character index of the first character in the line that the lineIndex parameter specifies.
TextField
  
Returns the text of the line specified by the lineIndex parameter.
TextField
  
Given a character index, returns the length of the paragraph containing the given character.
TextField
 Inherited
getRect(targetCoordinateSpace:DisplayObject):Rectangle
Returns a rectangle that defines the boundary of the display object, based on the coordinate system defined by the targetCoordinateSpace parameter, excluding any strokes on shapes.
DisplayObject
  
getTextFormat(beginIndex:int = -1, endIndex:int = -1):flash.text:TextFormat
Returns a TextFormat object that contains formatting information for the range of text that the beginIndex and endIndex parameters specify.
TextField
 Inherited
Converts the point object from the Stage (global) coordinates to the display object's (local) coordinates.
DisplayObject
 Inherited
Converts a two-dimensional point from the Stage (global) coordinates to a three-dimensional display object's (local) coordinates.
DisplayObject
 Inherited
Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
EventDispatcher
 Inherited
Indicates whether an object has a specified property defined.
Object
 Inherited
Evaluates the bounding box of the display object to see if it overlaps or intersects with the bounding box of the obj display object.
DisplayObject
 Inherited
hitTestPoint(x:Number, y:Number, shapeFlag:Boolean = false):Boolean
Evaluates the display object to see if it overlaps or intersects with the point specified by the x and y parameters.
DisplayObject
  
isFontCompatible(fontName:String, fontStyle:String):Boolean
[static] Returns true if an embedded font is available with the specified fontName and fontStyle where Font.fontType is flash.text.FontType.EMBEDDED.
TextField
 Inherited
Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter.
Object
 Inherited
Converts a three-dimensional point of the three-dimensional display object's (local) coordinates to a two-dimensional point in the Stage (global) coordinates.
DisplayObject
 Inherited
Converts the point object from the display object's (local) coordinates to the Stage (global) coordinates.
DisplayObject
 Inherited
Indicates whether the specified property exists and is enumerable.
Object
 Inherited
removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
Removes a listener from the EventDispatcher object.
EventDispatcher
  
Replaces the current selection with the contents of the value parameter.
TextField
  
replaceText(beginIndex:int, endIndex:int, newText:String):void
Replaces the range of characters that the beginIndex and endIndex parameters specify with the contents of the newText parameter.
TextField
 Inherited
Sets the availability of a dynamic property for loop operations.
Object
  
setSelection(beginIndex:int, endIndex:int):void
Sets as selected the text designated by the index values of the first and last characters, which are specified with the beginIndex and endIndex parameters.
TextField
  
setTextFormat(format:flash.text:TextFormat, beginIndex:int = -1, endIndex:int = -1):void
Applies the text formatting that the format parameter specifies to the specified text in a text field.
TextField
 Inherited
Returns the string representation of this object, formatted according to locale-specific conventions.
Object
 Inherited
Returns the string representation of the specified object.
Object
 Inherited
Returns the primitive value of the specified object.
Object
 Inherited
Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
EventDispatcher
Events
 Event Summary Defined By
 Inherited[broadcast event] Dispatched when the Flash Player or AIR application gains operating system focus and becomes active.EventDispatcher
 InheritedDispatched when a display object is added to the display list.DisplayObject
 InheritedDispatched when a display object is added to the on stage display list, either directly or through the addition of a sub tree in which the display object is contained.DisplayObject
  Dispatched after a control value is modified, unlike the textInput event, which is dispatched before the value is modified.TextField
 InheritedDispatched when the user selects 'Clear' (or 'Delete') from the text context menu.InteractiveObject
 InheritedDispatched when a user presses and releases the main button of the user's pointing device over the same InteractiveObject.InteractiveObject
 InheritedDispatched when a user gesture triggers the context menu associated with this interactive object in an AIR application.InteractiveObject
 InheritedDispatched when the user activates the platform specific accelerator key combination for a copy operation or selects 'Copy' from the text context menu.InteractiveObject
 InheritedDispatched when the user activates the platform specific accelerator key combination for a cut operation or selects 'Cut' from the text context menu.InteractiveObject
 Inherited[broadcast event] Dispatched when the Flash Player or AIR application operating loses system focus and is becoming inactive.EventDispatcher
 InheritedDispatched when a user presses and releases the main button of a pointing device twice in rapid succession over the same InteractiveObject when that object's doubleClickEnabled flag is set to true.InteractiveObject
 Inherited[broadcast event] Dispatched when the playhead is entering a new frame.DisplayObject
 Inherited[broadcast event] Dispatched when the playhead is exiting the current frame.DisplayObject
 InheritedDispatched after a display object gains focus.InteractiveObject
 InheritedDispatched after a display object loses focus.InteractiveObject
 Inherited[broadcast event] Dispatched after the constructors of frame display objects have run but before frame scripts have run.DisplayObject
 InheritedDispatched when the user moves a point of contact over the InteractiveObject instance on a touch-enabled device (such as moving a fingers from left to right over a display object on a mobile phone or tablet with a touch screen).InteractiveObject
 InheritedDispatched when the user creates a point of contact with an InteractiveObject instance, then taps on a touch-enabled device (such as placing several fingers over a display object to open a menu and then taps one finger to select a menu item on a mobile phone or tablet with a touch screen).InteractiveObject
 InheritedDispatched when the user performs a rotation gesture at a point of contact with an InteractiveObject instance (such as touching two fingers and rotating them over a display object on a mobile phone or tablet with a touch screen).InteractiveObject
 InheritedDispatched when the user performs a swipe gesture at a point of contact with an InteractiveObject instance (such as touching three fingers to a screen and then moving them in parallel over a display object on a mobile phone or tablet with a touch screen).InteractiveObject
 InheritedDispatched when the user presses two points of contact over the same InteractiveObject instance on a touch-enabled device (such as presses and releases two fingers over a display object on a mobile phone or tablet with a touch screen).InteractiveObject
 InheritedDispatched when the user performs a zoom gesture at a point of contact with an InteractiveObject instance (such as touching two fingers to a screen and then quickly spreading the fingers apart over a display object on a mobile phone or tablet with a touch screen).InteractiveObject
 InheritedThis event is dispatched to any client app that supports inline input with an IMEInteractiveObject
 InheritedDispatched when the user presses a key.InteractiveObject
 InheritedDispatched when the user attempts to change focus by using keyboard navigation.InteractiveObject
 InheritedDispatched when the user releases a key.InteractiveObject
  Dispatched when a user clicks a hyperlink in an HTML-enabled text field, where the URL begins with "event:".TextField
 InheritedDispatched when a user presses and releases the middle button of the user's pointing device over the same InteractiveObject.InteractiveObject
 InheritedDispatched when a user presses the middle pointing device button over an InteractiveObject instance.InteractiveObject
 InheritedDispatched when a user releases the pointing device button over an InteractiveObject instance.InteractiveObject
 InheritedDispatched when a user presses the pointing device button over an InteractiveObject instance.InteractiveObject
 InheritedDispatched when the user attempts to change focus by using a pointer device.InteractiveObject
 InheritedDispatched when a user moves the pointing device while it is over an InteractiveObject.InteractiveObject
 InheritedDispatched when the user moves a pointing device away from an InteractiveObject instance.InteractiveObject
 InheritedDispatched when the user moves a pointing device over an InteractiveObject instance.InteractiveObject
 InheritedDispatched when a user releases the pointing device button over an InteractiveObject instance.InteractiveObject
 InheritedDispatched when a mouse wheel is spun over an InteractiveObject instance.InteractiveObject
 InheritedDispatched by the drag initiator InteractiveObject when the user releases the drag gesture.InteractiveObject
 InheritedDispatched by the target InteractiveObject when a dragged object is dropped on it and the drop has been accepted with a call to DragManager.acceptDragDrop().InteractiveObject
 InheritedDispatched by an InteractiveObject when a drag gesture enters its boundary.InteractiveObject
 InheritedDispatched by an InteractiveObject when a drag gesture leaves its boundary.InteractiveObject
 InheritedDispatched by an InteractiveObject continually while a drag gesture remains within its boundary.InteractiveObject
 InheritedDispatched at the beginning of a drag operation by the InteractiveObject that is specified as the drag initiator in the DragManager.doDrag() call.InteractiveObject
 InheritedDispatched during a drag operation by the InteractiveObject that is specified as the drag initiator in the DragManager.doDrag() call.InteractiveObject
 InheritedDispatched when the user activates the platform specific accelerator key combination for a paste operation or selects 'Paste' from the text context menu.InteractiveObject
 InheritedDispatched when a display object is about to be removed from the display list.DisplayObject
 InheritedDispatched when a display object is about to be removed from the display list, either directly or through the removal of a sub tree in which the display object is contained.DisplayObject
 Inherited[broadcast event] Dispatched when the display list is about to be updated and rendered.DisplayObject
 InheritedDispatched when a user presses and releases the right button of the user's pointing device over the same InteractiveObject.InteractiveObject
 InheritedDispatched when a user presses the pointing device button over an InteractiveObject instance.InteractiveObject
 InheritedDispatched when a user releases the pointing device button over an InteractiveObject instance.InteractiveObject
 InheritedDispatched when the user moves a pointing device away from an InteractiveObject instance.InteractiveObject
 InheritedDispatched when the user moves a pointing device over an InteractiveObject instance.InteractiveObject
  Dispatched by a TextField object after the user scrolls.TextField
 InheritedDispatched when the user activates the platform specific accelerator key combination for a select all operation or selects 'Select All' from the text context menu.InteractiveObject
 InheritedDispatched when the value of the object's tabChildren flag changes.InteractiveObject
 InheritedDispatched when the object's tabEnabled flag changes.InteractiveObject
 InheritedDispatched when the value of the object's tabIndex property changes.InteractiveObject
  Flash Player dispatches the textInput event when a user enters one or more characters of text.TextField
 InheritedDispatched when the user first contacts a touch-enabled device (such as touches a finger to a mobile phone or tablet with a touch screen).InteractiveObject
 InheritedDispatched when the user removes contact with a touch-enabled device (such as lifts a finger off a mobile phone or tablet with a touch screen).InteractiveObject
 InheritedDispatched when the user moves the point of contact with a touch-enabled device (such as drags a finger across a mobile phone or tablet with a touch screen).InteractiveObject
 InheritedDispatched when the user moves the point of contact away from InteractiveObject instance on a touch-enabled device (such as drags a finger from one display object to another on a mobile phone or tablet with a touch screen).InteractiveObject
 InheritedDispatched when the user moves the point of contact over an InteractiveObject instance on a touch-enabled device (such as drags a finger from a point outside a display object to a point over a display object on a mobile phone or tablet with a touch screen).InteractiveObject
 InheritedDispatched when the user moves the point of contact away from an InteractiveObject instance on a touch-enabled device (such as drags a finger from over a display object to a point outisde the display object on a mobile phone or tablet with a touch screen).InteractiveObject
 InheritedDispatched when the user moves the point of contact over an InteractiveObject instance on a touch-enabled device (such as drags a finger from a point outside a display object to a point over a display object on a mobile phone or tablet with a touch screen).InteractiveObject
 InheritedDispatched when the user lifts the point of contact over the same InteractiveObject instance on which the contact was initiated on a touch-enabled device (such as presses and releases a finger from a single point over a display object on a mobile phone or tablet with a touch screen).InteractiveObject
Property Detail

alwaysShowSelection

property
alwaysShowSelection:Boolean

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

When set to true and the text field is not in focus, Flash Player highlights the selection in the text field in gray. When set to false and the text field is not in focus, Flash Player does not highlight the selection in the text field.

The default value is false.



Implementation
    public function get alwaysShowSelection():Boolean
    public function set alwaysShowSelection(value:Boolean):void

See also


Example  ( How to use this example )
Compile and run the following file. When you run the file, drag to select text in each of the two text fields, and notice the difference in selection highlighting when you select text in the two text fields (changing focus):

    package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFieldType;

    public class TextField_alwaysShowSelection extends Sprite {
        public function TextField_alwaysShowSelection() {
            var label1:TextField = createCustomTextField(0, 20, 200, 20);
            label1.text = "This text is selected.";
            label1.setSelection(0, 9);
            label1.alwaysShowSelection = true;

            var label2:TextField = createCustomTextField(0, 50, 200, 20);
            label2.text = "Drag to select some of this text.";
        }

        private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField {
            var result:TextField = new TextField();
            result.x = x; result.y = y;
            result.width = width; result.height = height;
            addChild(result);
            return result;
        }
    }
}

antiAliasType

property 
antiAliasType:String

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9

The type of anti-aliasing used for this text field. Use flash.text.AntiAliasType constants for this property. You can control this setting only if the font is embedded (with the embedFonts property set to true). The default setting is flash.text.AntiAliasType.NORMAL.

To set values for this property, use the following string values:

String valueDescription
flash.text.AntiAliasType.NORMALApplies the regular text anti-aliasing. This value matches the type of anti-aliasing that Flash Player 7 and earlier versions used.
flash.text.AntiAliasType.ADVANCEDApplies advanced anti-aliasing, which makes text more legible. (This feature became available in Flash Player 8.) Advanced anti-aliasing allows for high-quality rendering of font faces at small sizes. It is best used with applications with a lot of small text. Advanced anti-aliasing is not recommended for fonts that are larger than 48 points.



Implementation
    public function get antiAliasType():String
    public function set antiAliasType(value:String):void

See also

autoSize

property 
autoSize:String

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Controls automatic sizing and alignment of text fields. Acceptable values for the TextFieldAutoSize constants: TextFieldAutoSize.NONE (the default), TextFieldAutoSize.LEFT, TextFieldAutoSize.RIGHT, and TextFieldAutoSize.CENTER.

If autoSize is set to TextFieldAutoSize.NONE (the default) no resizing occurs.

If autoSize is set to TextFieldAutoSize.LEFT, the text is treated as left-justified text, meaning that the left margin of the text field remains fixed and any resizing of a single line of the text field is on the right margin. If the text includes a line break (for example, "\n" or "\r"), the bottom is also resized to fit the next line of text. If wordWrap is also set to true, only the bottom of the text field is resized and the right side remains fixed.

If autoSize is set to TextFieldAutoSize.RIGHT, the text is treated as right-justified text, meaning that the right margin of the text field remains fixed and any resizing of a single line of the text field is on the left margin. If the text includes a line break (for example, "\n" or "\r"), the bottom is also resized to fit the next line of text. If wordWrap is also set to true, only the bottom of the text field is resized and the left side remains fixed.

If autoSize is set to TextFieldAutoSize.CENTER, the text is treated as center-justified text, meaning that any resizing of a single line of the text field is equally distributed to both the right and left margins. If the text includes a line break (for example, "\n" or "\r"), the bottom is also resized to fit the next line of text. If wordWrap is also set to true, only the bottom of the text field is resized and the left and right sides remain fixed.



Implementation
    public function get autoSize():String
    public function set autoSize(value:String):void

Throws
ArgumentError — The autoSize specified is not a member of flash.text.TextFieldAutoSize.

See also

background

property 
background:Boolean

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Specifies whether the text field has a background fill. If true, the text field has a background fill. If false, the text field has no background fill. Use the backgroundColor property to set the background color of a text field.

The default value is false.



Implementation
    public function get background():Boolean
    public function set background(value:Boolean):void

See also

backgroundColor

property 
backgroundColor:uint

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

The color of the text field background. The default value is 0xFFFFFF (white). This property can be retrieved or set, even if there currently is no background, but the color is visible only if the text field has the background property set to true.



Implementation
    public function get backgroundColor():uint
    public function set backgroundColor(value:uint):void

See also

border

property 
border:Boolean

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Specifies whether the text field has a border. If true, the text field has a border. If false, the text field has no border. Use the borderColor property to set the border color.

The default value is false.



Implementation
    public function get border():Boolean
    public function set border(value:Boolean):void

See also

borderColor

property 
borderColor:uint

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

The color of the text field border. The default value is 0x000000 (black). This property can be retrieved or set, even if there currently is no border, but the color is visible only if the text field has the border property set to true.



Implementation
    public function get borderColor():uint
    public function set borderColor(value:uint):void

See also

bottomScrollV

property 
bottomScrollV:int  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

An integer (1-based index) that indicates the bottommost line that is currently visible in the specified text field. Think of the text field as a window onto a block of text. The scrollV property is the 1-based index of the topmost visible line in the window.

All the text between the lines indicated by scrollV and bottomScrollV is currently visible in the text field.



Implementation
    public function get bottomScrollV():int

See also

caretIndex

property 
caretIndex:int  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

The index of the insertion point (caret) position. If no insertion point is displayed, the value is the position the insertion point would be if you restored focus to the field (typically where the insertion point last was, or 0 if the field has not had focus).

Selection span indexes are zero-based (for example, the first position is 0, the second position is 1, and so on).



Implementation
    public function get caretIndex():int

See also


Example  ( How to use this example )
In this example, a TextField instance is created and populated with text. An event listener is assigned so that when the user clicks on the TextField, the printCursorPosition method is called. In that case, the values of the caretIndex, selectionBeginIndex, and selectionEndIndex properties are output.

Run this example and try clicking in the TextField to select text. Then click in the field without selecting text. When you click in the text without making a selection, the caretIndex property indicates where the insertion point occurs, and the selectionBeginIndex and selectionEndIndex properties equal the caretIndex property value.


package {
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.text.TextField;
    import flash.text.TextFieldType;

    public class TextField_caretIndex extends Sprite {
        public function TextField_caretIndex() {
            var tf:TextField = createCustomTextField(10, 10, 100, 100);
            tf.wordWrap = true;
            tf.type = TextFieldType.INPUT;
            tf.text = "Click in this text field. Compare the difference between clicking without selecting versus clicking and selecting text.";
            tf.addEventListener(MouseEvent.CLICK, printCursorPosition);
        }

        private function printCursorPosition(event:MouseEvent):void {
            var tf:TextField = TextField(event.target);
            trace("caretIndex:", tf.caretIndex);
            trace("selectionBeginIndex:", tf.selectionBeginIndex);
            trace("selectionEndIndex:", tf.selectionEndIndex);
        }

        private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField {
            var result:TextField = new TextField();
            result.x = x;
            result.y = y;
            result.width = width;
            result.height = height;
            addChild(result);
            return result;
        }
    }
}

condenseWhite

property 
condenseWhite:Boolean

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

A Boolean value that specifies whether extra white space (spaces, line breaks, and so on) in a text field with HTML text is removed. The default value is false. The condenseWhite property only affects text set with the htmlText property, not the text property. If you set text with the text property, condenseWhite is ignored.

If condenseWhite is set to true, use standard HTML commands such as <BR> and <P> to place line breaks in the text field.

Set the condenseWhite property before setting the htmlText property.



Implementation
    public function get condenseWhite():Boolean
    public function set condenseWhite(value:Boolean):void

See also


Example  ( How to use this example )
The following shows the difference between setting the condenseWhite setting to false and setting it to true:

package {
    import flash.display.Sprite;
    import flash.text.TextField;

    public class TextField_condenseWhite extends Sprite {
        public function TextField_condenseWhite() {
            var tf1:TextField = createCustomTextField(0, 0, 200, 50);
            tf1.condenseWhite = false;
            tf1.htmlText = "keep    on\n\ttruckin'";
            
            var tf2:TextField = createCustomTextField(0, 120, 200, 50);
            tf2.condenseWhite = true;
            tf2.htmlText = "keep    on\n\ttruckin'";
        }

        private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField {
            var result:TextField = new TextField();
            result.x = x;
            result.y = y;
            result.width = width;
            result.height = height;
            result.border = true;
            addChild(result);
            return result;
        }
    }
}

defaultTextFormat

property 
defaultTextFormat:flash.text:TextFormat

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Specifies the format applied to newly inserted text, such as text entered by a user or text inserted with the replaceSelectedText() method.

Note: When selecting characters to be replaced with setSelection() and replaceSelectedText(), the defaultTextFormat will be applied only if the text has been selected up to and including the last character. Here is an example:

     var my_txt:TextField new TextField();
     my_txt.text = "Flash Macintosh version";
     var my_fmt:TextFormat = new TextFormat();
     my_fmt.color = 0xFF0000;
     my_txt.defaultTextFormat = my_fmt;
     my_txt.setSelection(6,15); // partial text selected - defaultTextFormat not applied
     my_txt.setSelection(6,23); // text selected to end - defaultTextFormat applied
     my_txt.replaceSelectedText("Windows version");
     

When you access the defaultTextFormat property, the returned TextFormat object has all of its properties defined. No property is null.

Note: You can't set this property if a style sheet is applied to the text field.



Implementation
    public function get defaultTextFormat():flash.text:TextFormat
    public function set defaultTextFormat(value:flash.text:TextFormat):void

Throws
Error — This method cannot be used on a text field with a style sheet.

See also

displayAsPassword

property 
displayAsPassword:Boolean

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Specifies whether the text field is a password text field. If the value of this property is true, the text field is treated as a password text field and hides the input characters using asterisks instead of the actual characters. If false, the text field is not treated as a password text field. When password mode is enabled, the Cut and Copy commands and their corresponding keyboard shortcuts will not function. This security mechanism prevents an unscrupulous user from using the shortcuts to discover a password on an unattended computer.

The default value is false.



Implementation
    public function get displayAsPassword():Boolean
    public function set displayAsPassword(value:Boolean):void

embedFonts

property 
embedFonts:Boolean

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Specifies whether to render by using embedded font outlines. If false, Flash Player renders the text field by using device fonts.

If you set the embedFonts property to true for a text field, you must specify a font for that text by using the font property of a TextFormat object applied to the text field. If the specified font is not embedded in the SWF file, the text is not displayed.

The default value is false.



Implementation
    public function get embedFonts():Boolean
    public function set embedFonts(value:Boolean):void

See also

gridFitType

property 
gridFitType:String

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9

The type of grid fitting used for this text field. This property applies only if the flash.text.AntiAliasType property of the text field is set to flash.text.AntiAliasType.ADVANCED.

The type of grid fitting used determines whether Flash Player forces strong horizontal and vertical lines to fit to a pixel or subpixel grid, or not at all.

For the flash.text.GridFitType property, you can use the following string values:

String valueDescription
flash.text.GridFitType.NONESpecifies no grid fitting. Horizontal and vertical lines in the glyphs are not forced to the pixel grid. This setting is recommended for animation or for large font sizes.
flash.text.GridFitType.PIXELSpecifies that strong horizontal and vertical lines are fit to the pixel grid. This setting works only for left-aligned text fields. To use this setting, the flash.dispaly.AntiAliasType property of the text field must be set to flash.text.AntiAliasType.ADVANCED. This setting generally provides the best legibility for left-aligned text.
flash.text.GridFitType.SUBPIXELSpecifies that strong horizontal and vertical lines are fit to the subpixel grid on an LCD monitor. To use this setting, the flash.text.AntiAliasType property of the text field must be set to flash.text.AntiAliasType.ADVANCED. The flash.text.GridFitType.SUBPIXEL setting is often good for right-aligned or centered dynamic text, and it is sometimes a useful trade-off for animation versus text quality.

The default value is pixel.



Implementation
    public function get gridFitType():String
    public function set gridFitType(value:String):void

See also


Example  ( How to use this example )
The following example shows three text fields with different settings for the gridFitType property. When you use this example, notice the difference in legibility for the first two lines. Also note the optimal use of GridFitType.PIXEL for left-aligned text and GridFitType.SUBPIXEL for right-aligned text.

package
{
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFormat;
    import flash.text.TextFieldAutoSize;
    import flash.text.AntiAliasType;
    import flash.text.GridFitType;

    public class gridFitTypeExample extends Sprite
    {
        public function gridFitTypeExample()
        {
    var format1:TextFormat = new TextFormat();
    format1.font="Arial";
    format1.size=12;

    var tf1:TextField = createCustomTextField(0,0,format1,"NONE",TextFieldAutoSize.LEFT,GridFitType.NONE);
    
    var tf2:TextField = createCustomTextField(0,30,format1,"PIXEL",TextFieldAutoSize.LEFT,GridFitType.PIXEL);

    var tf3:TextField = createCustomTextField(300,60,format1,"SUBPIXEL",TextFieldAutoSize.RIGHT,GridFitType.SUBPIXEL);

        }
        private function createCustomTextField(x:Number,y:Number,fm:TextFormat,tl:String,tfs:String,gft:String):TextField 
        {
            var result:TextField = new TextField();
            result.x=x;
            result.y=y;
            result.embedFonts=true;
            result.antiAliasType=AntiAliasType.ADVANCED;
            result.text="This text uses a gridFitType of " + tl;
            result.autoSize=tfs;
        result.gridFitType=gft;
            result.setTextFormat(fm);
            addChild(result);
            return result;
        }
    }
}

htmlText

property 
htmlText:String

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Contains the HTML representation of the text field contents.

Flash Player supports the following HTML tags:

Tag Description
Anchor tag The <a> tag creates a hypertext link and supports the following attributes:
  • target: Specifies the name of the target window where you load the page. Options include _self, _blank, _parent, and _top. The _self option specifies the current frame in the current window, _blank specifies a new window, _parent specifies the parent of the current frame, and _top specifies the top-level frame in the current window.
  • href: Specifies a URL or an ActionScript link event.The URL can be either absolute or relative to the location of the SWF file that is loading the page. An example of an absolute reference to a URL is http://www.adobe.com; an example of a relative reference is /index.html. Absolute URLs must be prefixed with http://; otherwise, Flash Player or AIR treats them as relative URLs. You can use the link event to cause the link to execute an ActionScript function in a SWF file instead of opening a URL. To specify a link event, use the event scheme instead of the http scheme in your href attribute. An example is href="event:myText" instead of href="http://myURL"; when the user clicks a hypertext link that contains the event scheme, the text field dispatches a link TextEvent with its text property set to "myText". You can then create an ActionScript function that executes whenever the link TextEvent is dispatched. You can also define a:link, a:hover, and a:active styles for anchor tags by using style sheets.
Bold tag The <b> tag renders text as bold. A bold typeface must be available for the font used.
Break tag The <br> tag creates a line break in the text field. Set the text field to be a multiline text field to use this tag.
Font tag The <font> tag specifies a font or list of fonts to display the text.The font tag supports the following attributes:
  • color: Only hexadecimal color (#FFFFFF) values are supported.
  • face: Specifies the name of the font to use. As shown in the following example, you can specify a list of comma-delimited font names, in which case Flash Player selects the first available font. If the specified font is not installed on the local computer system or isn't embedded in the SWF file, Flash Player selects a substitute font.
  • size: Specifies the size of the font. You can use absolute pixel sizes, such as 16 or 18, or relative point sizes, such as +2 or -4.
Image tag The <img> tag lets you embed external image files (JPEG, GIF, PNG), SWF files, and movie clips inside text fields. Text automatically flows around images you embed in text fields. You must set the text field to be multiline to wrap text around an image.

The <img> tag supports the following attributes:

  • src: Specifies the URL to an image or SWF file, or the linkage identifier for a movie clip symbol in the library. This attribute is required; all other attributes are optional. External files (JPEG, GIF, PNG, and SWF files) do not show until they are downloaded completely.
  • width: The width of the image, SWF file, or movie clip being inserted, in pixels.
  • height: The height of the image, SWF file, or movie clip being inserted, in pixels.
  • align: Specifies the horizontal alignment of the embedded image within the text field. Valid values are left and right. The default value is left.
  • hspace: Specifies the amount of horizontal space that surrounds the image where no text appears. The default value is 8.
  • vspace: Specifies the amount of vertical space that surrounds the image where no text appears. The default value is 8.
  • id: Specifies the name for the movie clip instance (created by Flash Player) that contains the embedded image file, SWF file, or movie clip. This approach is used to control the embedded content with ActionScript.
  • checkPolicyFile: Specifies that Flash Player checks for a URL policy file on the server associated with the image domain. If a policy file exists, SWF files in the domains listed in the file can access the data of the loaded image, for example, by calling the BitmapData.draw() method with this image as the source parameter. For more information related to security, see the Flash Player Developer Center Topic: Security.

Flash displays media embedded in a text field at full size. To specify the dimensions of the media you are embedding, use the <img> tag height and width attributes.

In general, an image embedded in a text field appears on the line following the <img> tag. However, when the <img> tag is the first character in the text field, the image appears on the first line of the text field.

For AIR content in the application security sandbox, AIR ignores img tags in HTML content in ActionScript TextField objects. This is to prevent possible phishing attacks,

Italic tag The <i> tag displays the tagged text in italics. An italic typeface must be available for the font used.
List item tag The <li> tag places a bullet in front of the text that it encloses. Note: Because Flash Player and AIR do not recognize ordered and unordered list tags (<ol> and <ul>, they do not modify how your list is rendered. All lists are unordered and all list items use bullets.
Paragraph tag The <p> tag creates a new paragraph. The text field must be set to be a multiline text field to use this tag. The <p> tag supports the following attributes:
  • align: Specifies alignment of text within the paragraph; valid values are left, right, justify, and center.
  • class: Specifies a CSS style class defined by a flash.text.StyleSheet object.
Span tag The <span> tag is available only for use with CSS text styles. It supports the following attribute:
  • class: Specifies a CSS style class defined by a flash.text.StyleSheet object.
Text format tag

The <textformat> tag lets you use a subset of paragraph formatting properties of the TextFormat class within text fields, including line leading, indentation, margins, and tab stops. You can combine <textformat> tags with the built-in HTML tags.

The <textformat> tag has the following attributes:

  • blockindent: Specifies the block indentation in points; corresponds to TextFormat.blockIndent.
  • indent: Specifies the indentation from the left margin to the first character in the paragraph; corresponds to TextFormat.indent. Both positive and negative numbers are acceptable.
  • leading: Specifies the amount of leading (vertical space) between lines; corresponds to TextFormat.leading. Both positive and negative numbers are acceptable.
  • leftmargin: Specifies the left margin of the paragraph, in points; corresponds to TextFormat.leftMargin.
  • rightmargin: Specifies the right margin of the paragraph, in points; corresponds to TextFormat.rightMargin.
  • tabstops: Specifies custom tab stops as an array of non-negative integers; corresponds to TextFormat.tabStops.
Underline tag The <u> tag underlines the tagged text.

Flash Player and AIR support the following HTML entities:

Entity Description
&lt; < (less than)
&gt; > (greater than)
&amp; & (ampersand)
&quot; " (double quotes)
&apos; ' (apostrophe, single quote)

Flash Player and AIR also support explicit character codes, such as &#38; (ASCII ampersand) and &#x20AC; (Unicode € symbol).



Implementation
    public function get htmlText():String
    public function set htmlText(value:String):void

See also


Example  ( How to use this example )
The following example creates a TextField called tf1, and assigns an HTML-formatted String to its text property. When its htmlText property is traced, the output is the HTML-formatted String, with additional tags (such as <P> and <FONT>) automatically added by Flash Player. When the value of the text property is traced, the unformatted string without HTML tags is displayed.

By way of comparison, the same steps are performed on another TextField object named tf2, with the addition that a StyleSheet object is assigned to tf2's styleSheet property before its htmlText property is set. In that case, when the htmlText property is traced, it only includes the exact HTML text that was originally assigned to the htmlText property, showing that no additional tags were added by Flash Player.


package {
    import flash.display.Sprite;
    import flash.text.StyleSheet;
    import flash.text.TextField;

    public class TextField_text extends Sprite {
        public function TextField_text() {
            var tf1:TextField = createCustomTextField(10, 10, 400, 22);
            tf1.htmlText = "<b>Lorem ipsum dolor sit amet.</b>";

            // htmlText: <P ALIGN="LEFT"><FONT FACE="Times New Roman" SIZE="12" COLOR="#000000" LETTERSPACING="0" KERNING="0"><b>Lorem ipsum dolor sit amet.</b></FONT></P>
            trace("htmlText: " + tf1.htmlText);
            // text: Lorem ipsum dolor sit amet.
            trace("text: " + tf1.text);
            
            var tf2:TextField = createCustomTextField(10, 50, 400, 22);
            tf2.styleSheet = new StyleSheet();
            tf2.htmlText = "<b>Lorem ipsum dolor sit amet.</b>";
            // htmlText: <b>Lorem ipsum dolor sit amet.</b>
            trace("htmlText: " + tf2.htmlText);
            // text: Lorem ipsum dolor sit amet.
            trace("text: " + tf2.text);
        }

        private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField {
            var result:TextField = new TextField();
            result.x = x;
            result.y = y;
            result.width = width;
            result.height = height;
            addChild(result);
            return result;
        }
    }
}

length

property 
length:int  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

The number of characters in a text field. A character such as tab (\t) counts as one character.



Implementation
    public function get length():int

maxChars

property 
maxChars:int

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

The maximum number of characters that the text field can contain, as entered by a user. A script can insert more text than maxChars allows; the maxChars property indicates only how much text a user can enter. If the value of this property is 0, a user can enter an unlimited amount of text.

The default value is 0.



Implementation
    public function get maxChars():int
    public function set maxChars(value:int):void

maxScrollH

property 
maxScrollH:int  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

The maximum value of scrollH.



Implementation
    public function get maxScrollH():int

See also

maxScrollV

property 
maxScrollV:int  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

The maximum value of scrollV.



Implementation
    public function get maxScrollV():int

See also

mouseWheelEnabled

property 
mouseWheelEnabled:Boolean

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9

A Boolean value that indicates whether Flash Player automatically scrolls multiline text fields when the user clicks a text field and rolls the mouse wheel. By default, this value is true. This property is useful if you want to prevent mouse wheel scrolling of text fields, or implement your own text field scrolling.



Implementation
    public function get mouseWheelEnabled():Boolean
    public function set mouseWheelEnabled(value:Boolean):void

multiline

property 
multiline:Boolean

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Indicates whether field is a multiline text field. If the value is true, the text field is multiline; if the value is false, the text field is a single-line text field. In a field of type TextFieldType.INPUT, the multiline value determines whether the Enter key creates a new line (a value of false, and the Enter key is ignored). If you paste text into a TextField with a multiline value of false, newlines are stripped out of the text.

The default value is false.



Implementation
    public function get multiline():Boolean
    public function set multiline(value:Boolean):void

See also

numLines

property 
numLines:int  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Defines the number of text lines in a multiline text field. If wordWrap property is set to true, the number of lines increases when text wraps.



Implementation
    public function get numLines():int

See also

restrict

property 
restrict:String

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Indicates the set of characters that a user can enter into the text field. If the value of the restrict property is null, you can enter any character. If the value of the restrict property is an empty string, you cannot enter any character. If the value of the restrict property is a string of characters, you can enter only characters in the string into the text field. The string is scanned from left to right. You can specify a range by using the hyphen (-) character. Only user interaction is restricted; a script can put any text into the text field. This property does not synchronize with the Embed font options in the Property inspector.

If the string begins with a caret (^) character, all characters are initially accepted and succeeding characters in the string are excluded from the set of accepted characters. If the string does not begin with a caret (^) character, no characters are initially accepted and succeeding characters in the string are included in the set of accepted characters.

The following example allows only uppercase characters, spaces, and numbers to be entered into a text field:

     my_txt.restrict = "A-Z 0-9";
     

The following example includes all characters, but excludes lowercase letters:

     my_txt.restrict = "^a-z";
     

You can use a backslash to enter a ^ or - verbatim. The accepted backslash sequences are \-, \^ or \\. The backslash must be an actual character in the string, so when specified in ActionScript, a double backslash must be used. For example, the following code includes only the dash (-) and caret (^):

     my_txt.restrict = "\\-\\^";
     

The ^ can be used anywhere in the string to toggle between including characters and excluding characters. The following code includes only uppercase letters, but excludes the uppercase letter Q:

     my_txt.restrict = "A-Z^Q";
     

You can use the \u escape sequence to construct restrict strings. The following code includes only the characters from ASCII 32 (space) to ASCII 126 (tilde).

     my_txt.restrict = "\u0020-\u007E";
     

The default value is null.



Implementation
    public function get restrict():String
    public function set restrict(value:String):void

scrollH

property 
scrollH:int

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

The current horizontal scrolling position. If the scrollH property is 0, the text is not horizontally scrolled. This property value is an integer that represents the horizontal position in pixels.

The units of horizontal scrolling are pixels, whereas the units of vertical scrolling are lines. Horizontal scrolling is measured in pixels because most fonts you typically use are proportionally spaced; that is, the characters can have different widths. Flash Player performs vertical scrolling by line because users usually want to see a complete line of text rather than a partial line. Even if a line uses multiple fonts, the height of the line adjusts to fit the largest font in use.

Note: The scrollH property is zero-based, not 1-based like the scrollV vertical scrolling property.



Implementation
    public function get scrollH():int
    public function set scrollH(value:int):void

See also

scrollV

property 
scrollV:int

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

The vertical position of text in a text field. The scrollV property is useful for directing users to a specific paragraph in a long passage, or creating scrolling text fields.

The units of vertical scrolling are lines, whereas the units of horizontal scrolling are pixels. If the first line displayed is the first line in the text field, scrollV is set to 1 (not 0). Horizontal scrolling is measured in pixels because most fonts are proportionally spaced; that is, the characters can have different widths. Flash performs vertical scrolling by line because users usually want to see a complete line of text rather than a partial line. Even if there are multiple fonts on a line, the height of the line adjusts to fit the largest font in use.



Implementation
    public function get scrollV():int
    public function set scrollV(value:int):void

See also

selectable

property 
selectable:Boolean

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

A Boolean value that indicates whether the text field is selectable. The value true indicates that the text is selectable. The selectable property controls whether a text field is selectable, not whether a text field is editable. A dynamic text field can be selectable even if it is not editable. If a dynamic text field is not selectable, the user cannot select its text.

If selectable is set to false, the text in the text field does not respond to selection commands from the mouse or keyboard, and the text cannot be copied with the Copy command. If selectable is set to true, the text in the text field can be selected with the mouse or keyboard, and the text can be copied with the Copy command. You can select text this way even if the text field is a dynamic text field instead of an input text field.

The default value is true.



Implementation
    public function get selectable():Boolean
    public function set selectable(value:Boolean):void

See also


Example  ( How to use this example )
The following example creates two dynamic text fields: one text field with the selectable property set to true, and the other text field with the selectable property set to false. When you use this example, try to select the text in these fields with the mouse or the keyboard.

package
{
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;

    public class selectableExample extends Sprite
    {
        public function selectableExample()
        {
    var tf1:TextField = createCustomTextField(10, 10);
    tf1.text="This text can be selected";
    tf1.selectable=true;

    var tf2:TextField = createCustomTextField(10, 30);
    tf2.text="This text cannot be selected";
    tf2.selectable=false;
        }

        private function createCustomTextField(x:Number, y:Number):TextField 
       {
            var result:TextField = new TextField();
            result.x = x;
            result.y = y;
            result.autoSize=TextFieldAutoSize.LEFT;
            addChild(result);
            return result;
        }
    }
}

selectionBeginIndex

property 
selectionBeginIndex:int  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

The zero-based character index value of the first character in the current selection. For example, the first character is 0, the second character is 1, and so on. If no text is selected, this property is the value of caretIndex.



Implementation
    public function get selectionBeginIndex():int

See also


Example  ( How to use this example )
In this example, a TextField instance is created and populated with text. An event listener is assigned so that when the user clicks on the TextField, the printCursorPosition method is called. In that case, the values of the caretIndex, selectionBeginIndex, and selectionEndIndex properties are output.

Run this example and try clicking in the TextField to select text. Then click in the field without selecting text. When you click in the text without making a selection, the caretIndex property indicates where the insertion point occurs, and the selectionBeginIndex and selectionEndIndex properties equal the caretIndex property value.


package {
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.text.TextField;
    import flash.text.TextFieldType;

    public class TextField_caretIndex extends Sprite {
        public function TextField_caretIndex() {
            var tf:TextField = createCustomTextField(10, 10, 100, 100);
            tf.wordWrap = true;
            tf.type = TextFieldType.INPUT;
            tf.text = "Click in this text field. Compare the difference between clicking without selecting versus clicking and selecting text.";
            tf.addEventListener(MouseEvent.CLICK, printCursorPosition);
        }

        private function printCursorPosition(event:MouseEvent):void {
            var tf:TextField = TextField(event.target);
            trace("caretIndex:", tf.caretIndex);
            trace("selectionBeginIndex:", tf.selectionBeginIndex);
            trace("selectionEndIndex:", tf.selectionEndIndex);
        }

        private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField {
            var result:TextField = new TextField();
            result.x = x;
            result.y = y;
            result.width = width;
            result.height = height;
            addChild(result);
            return result;
        }
    }
}

selectionEndIndex

property 
selectionEndIndex:int  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

The zero-based character index value of the last character in the current selection. For example, the first character is 0, the second character is 1, and so on. If no text is selected, this property is the value of caretIndex.



Implementation
    public function get selectionEndIndex():int

See also


Example  ( How to use this example )
In this example, a TextField instance is created and populated with text. An event listener is assigned so that when the user clicks on the TextField, the printCursorPosition method is called. In that case, the values of the caretIndex, selectionBeginIndex, and selectionEndIndex properties are output.

Run this example and try clicking in the TextField to select text. Then click in the field without selecting text. When you click in the text without making a selection, the caretIndex property indicates where the insertion point occurs, and the selectionBeginIndex and selectionEndIndex properties equal the caretIndex property value.


package {
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.text.TextField;
    import flash.text.TextFieldType;

    public class TextField_caretIndex extends Sprite {
        public function TextField_caretIndex() {
            var tf:TextField = createCustomTextField(10, 10, 100, 100);
            tf.wordWrap = true;
            tf.type = TextFieldType.INPUT;
            tf.text = "Click in this text field. Compare the difference between clicking without selecting versus clicking and selecting text.";
            tf.addEventListener(MouseEvent.CLICK, printCursorPosition);
        }

        private function printCursorPosition(event:MouseEvent):void {
            var tf:TextField = TextField(event.target);
            trace("caretIndex:", tf.caretIndex);
            trace("selectionBeginIndex:", tf.selectionBeginIndex);
            trace("selectionEndIndex:", tf.selectionEndIndex);
        }

        private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField {
            var result:TextField = new TextField();
            result.x = x;
            result.y = y;
            result.width = width;
            result.height = height;
            addChild(result);
            return result;
        }
    }
}

sharpness

property 
sharpness:Number

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9

The sharpness of the glyph edges in this text field. This property applies only if the flash.text.AntiAliasType property of the text field is set to flash.text.AntiAliasType.ADVANCED. The range for sharpness is a number from -400 to 400. If you attempt to set sharpness to a value outside that range, Flash sets the property to the nearest value in the range (either -400 or 400).

The default value is 0.



Implementation
    public function get sharpness():Number
    public function set sharpness(value:Number):void

See also


Example  ( How to use this example )
The following example shows the effect of changing the sharpness property for a TextField object. You need to embed the font, and set the antiAliasType property to ADVANCED.

package
{
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.text.AntiAliasType;
    import flash.text.GridFitType;
    import flash.text.TextFormat;

    public class sharpnessExample extends Sprite
    {
        public function sharpnessExample()
        {
    var format1:TextFormat = new TextFormat();
    format1.font="Arial";
    format1.size=24;
    var lTxt:String = "The quick brown fox";

    var tf1:TextField=createCustomTextField(0,lTxt,format1,-400);
    var tf2:TextField=createCustomTextField(30,lTxt,format1,0);
    var tf3:TextField=createCustomTextField(60,lTxt,format1,400);
        }

        private function createCustomTextField(y:Number,fldTxt:String,format:TextFormat,fldSharpness:Number):TextField 
       {
            var result:TextField = new TextField();
            result.y=y;
            result.text=fldTxt;
            result.embedFonts=true;
            result.autoSize=TextFieldAutoSize.LEFT;
            result.antiAliasType=AntiAliasType.ADVANCED;
            result.gridFitType=GridFitType.PIXEL;
            result.sharpness=fldSharpness;
            result..setTextFormat(format);
            addChild(result);
            return result;
        }
    }
}

styleSheet

property 
styleSheet:StyleSheet

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Attaches a style sheet to the text field. For information on creating style sheets, see the StyleSheet class and the ActionScript 3.0 Developer's Guide.

You can change the style sheet associated with a text field at any time. If you change the style sheet in use, the text field is redrawn with the new style sheet. You can set the style sheet to null or undefined to remove the style sheet. If the style sheet in use is removed, the text field is redrawn without a style sheet.

Note: If the style sheet is removed, the contents of both TextField.text and TextField.htmlText change to incorporate the formatting previously applied by the style sheet. To preserve the original TextField.htmlText contents without the formatting, save the value in a variable before removing the style sheet.



Implementation
    public function get styleSheet():StyleSheet
    public function set styleSheet(value:StyleSheet):void

See also


Example  ( How to use this example )
The following example defines a simple StyleSheet object and assigns it to a text field with HTML content. Set the stylesheet property before setting the content.

package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.StyleSheet;

    public class TextStylesheetExample extends Sprite {
        var myLabel:TextField = new TextField();
        var labelText:String = "Hello world.";
        var newStyle:StyleSheet = new StyleSheet();

        public function TextStylesheetExample()
       {
            var styleObj:Object = new Object();
            styleObj.fontWeight = "bold";
            styleObj.color = "#660066";
            newStyle.setStyle(".defStyle", styleObj);

            myLabel.styleSheet=newStyle;
            myLabel.htmlText=labelText;
            addChild(myLabel);
        }
    }
}

text

property 
text:String

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

A string that is the current text in the text field. Lines are separated by the carriage return character ('\r', ASCII 13). This property contains unformatted text in the text field, without HTML tags.

To get the text in HTML form, use the htmlText property.



Implementation
    public function get text():String
    public function set text(value:String):void

See also


Example  ( How to use this example )
The following example creates a TextField called tf1, and assigns an HTML-formatted String to its text property. When its htmlText property is traced, the output is the HTML-formatted String, with additional tags (such as <P> and <FONT>) automatically added by Flash Player. When the value of the text property is traced, the unformatted string without HTML tags is displayed.

By way of comparison, the same steps are performed on another TextField object named tf2, with the addition that a StyleSheet object is assigned to tf2's styleSheet property before its htmlText property is set. In that case, when the htmlText property is traced, it only includes the exact HTML text that was originally assigned to the htmlText property, showing that no additional tags were added by Flash Player.


package {
    import flash.display.Sprite;
    import flash.text.StyleSheet;
    import flash.text.TextField;

    public class TextField_text extends Sprite {
        public function TextField_text() {
            var tf1:TextField = createCustomTextField(10, 10, 400, 22);
            tf1.htmlText = "<b>Lorem ipsum dolor sit amet.</b>";

            // htmlText: <P ALIGN="LEFT"><FONT FACE="Times New Roman" SIZE="12" COLOR="#000000" LETTERSPACING="0" KERNING="0"><b>Lorem ipsum dolor sit amet.</b></FONT></P>
            trace("htmlText: " + tf1.htmlText);
            // text: Lorem ipsum dolor sit amet.
            trace("text: " + tf1.text);
            
            var tf2:TextField = createCustomTextField(10, 50, 400, 22);
            tf2.styleSheet = new StyleSheet();
            tf2.htmlText = "<b>Lorem ipsum dolor sit amet.</b>";
            // htmlText: <b>Lorem ipsum dolor sit amet.</b>
            trace("htmlText: " + tf2.htmlText);
            // text: Lorem ipsum dolor sit amet.
            trace("text: " + tf2.text);
        }

        private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField {
            var result:TextField = new TextField();
            result.x = x;
            result.y = y;
            result.width = width;
            result.height = height;
            addChild(result);
            return result;
        }
    }
}

textColor

property 
textColor:uint

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

The color of the text in a text field, in hexadecimal format. The hexadecimal color system uses six digits to represent color values. Each digit has 16 possible values or characters. The characters range from 0-9 and then A-F. For example, black is 0x000000; white is 0xFFFFFF.

The default value is 0 (0x000000).



Implementation
    public function get textColor():uint
    public function set textColor(value:uint):void

Example  ( How to use this example )
The following ActionScript creates a TextField object and changes its textColor property to red (0xFF0000).

package {
    import flash.display.Sprite;
    import flash.text.TextField;

    public class TextField_textColor extends Sprite {
        public function TextField_textColor() {
            var tf:TextField = createCustomTextField(10, 10, 100, 300);
            tf.text = "This will be red text";
            tf.textColor = 0xFF0000;            
        }

        private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField {
            var result:TextField = new TextField();
            result.x = x;
            result.y = y;
            result.width = width;
            result.height = height;
            addChild(result);
            return result;
        }
    }
}

textHeight

property 
textHeight:Number  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

The height of the text in pixels.



Implementation
    public function get textHeight():Number

See also


Example  ( How to use this example )
The following example creates a TextField object and assigns text to it. The trace statements display the values of the textWidth and textHeight properties. For comparison, the width and height properties are also displayed. (Note that the values you see for textHeight and textWidth might vary depending on the font that is used on your machine).

package {
    import flash.display.Sprite;
    import flash.text.TextField;

    public class TextField_textHeight extends Sprite {
        public function TextField_textHeight() {
            var tf:TextField = createCustomTextField(10, 10, 100, 150);
            tf.text = "Sample text";
            
            trace("textWidth: " + tf.textWidth); // textWidth: 55.75
            trace("textHeight: " + tf.textHeight); // textHeight: 13.450000000000001
            trace("width: " + tf.width); // width: 100
            trace("height: " + tf.height); // height: 150
        }

        private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField {
            var result:TextField = new TextField();
            result.x = x;
            result.y = y;
            result.width = width;
            result.height = height;
            result.border = true;
            result.background = true;
            addChild(result);
            return result;
        }
    }
}

textWidth

property 
textWidth:Number  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

The width of the text in pixels.



Implementation
    public function get textWidth():Number

See also


Example  ( How to use this example )
The following example creates a TextField object and assigns text to it. The trace statements display the values of the textWidth and textHeight properties. For comparison, the width and height properties are also displayed. (Note that the values you see for textHeight and textWidth might vary depending on the font that is used on your machine).

package {
    import flash.display.Sprite;
    import flash.text.TextField;

    public class TextField_textHeight extends Sprite {
        public function TextField_textHeight() {
            var tf:TextField = createCustomTextField(10, 10, 100, 150);
            tf.text = "Sample text";
            
            trace("textWidth: " + tf.textWidth); // textWidth: 55.75
            trace("textHeight: " + tf.textHeight); // textHeight: 13.450000000000001
            trace("width: " + tf.width); // width: 100
            trace("height: " + tf.height); // height: 150
        }

        private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField {
            var result:TextField = new TextField();
            result.x = x;
            result.y = y;
            result.width = width;
            result.height = height;
            result.border = true;
            result.background = true;
            addChild(result);
            return result;
        }
    }
}

thickness

property 
thickness:Number

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9

The thickness of the glyph edges in this text field. This property applies only when flash.text.AntiAliasType is set to flash.text.AntiAliasType.ADVANCED.

The range for thickness is a number from -200 to 200. If you attempt to set thickness to a value outside that range, the property is set to the nearest value in the range (either -200 or 200).

The default value is 0.



Implementation
    public function get thickness():Number
    public function set thickness(value:Number):void

See also


Example  ( How to use this example )
The following example shows the effect of changing the thickness property for a TextField object. You need to embed the font, and set the antiAliasType property to ADVANCED.

package
{
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.text.AntiAliasType;
    import flash.text.GridFitType;
    import flash.text.TextFormat;

    public class thicknessExample extends Sprite
    {
        public function thicknessExample()
        {
    var format1:TextFormat = new TextFormat();
    format1.font="Arial";
    format1.size=24;
    var lTxt:String = "The quick brown fox";

    var tf1:TextField=createCustomTextField(0,lTxt,format1,-200);
    var tf2:TextField=createCustomTextField(30,lTxt,format1,0);
    var tf3:TextField=createCustomTextField(60,lTxt,format1,200);
        }

        private function createCustomTextField(y:Number,fldTxt:String,format:TextFormat,fldThickness:Number):TextField 
       {
            var result:TextField = new TextField();
            result.y=y;
            result.text=fldTxt;
            result.embedFonts=true;
            result.autoSize=TextFieldAutoSize.LEFT;
            result.antiAliasType=AntiAliasType.ADVANCED;
            result.gridFitType=GridFitType.PIXEL;
            result.thickness=fldThickness;
            result.setTextFormat(format);
            addChild(result);
            return result;
        }
    }
}

type

property 
type:String

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

The type of the text field. Either one of the following TextFieldType constants: TextFieldType.DYNAMIC, which specifies a dynamic text field, which a user cannot edit, or TextFieldType.INPUT, which specifies an input text field, which a user can edit.

The default value is dynamic.



Implementation
    public function get type():String
    public function set type(value:String):void

Throws
ArgumentError — The type specified is not a member of flash.text.TextFieldType.

See also


Example  ( How to use this example )
The following example creates two text fields: tfDynamic and tfInput. Text is entered into both text fields. However, tfDynamic has its type property set to TextFieldType.DYNAMIC, and tfInput has its type property set to TextFieldType.INPUT, so the user can modify the text in tfInput but can only view the text in tfDynamic.

package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFieldType;

    public class TextField_type extends Sprite {
        public function TextField_type() {
            var tfDynamic:TextField = createCustomTextField(10, 10, 100, 20);
            tfDynamic.type = TextFieldType.DYNAMIC;
            tfDynamic.text = "hello";

            var tfInput:TextField = createCustomTextField(10, 45, 100, 20);
            tfInput.type = TextFieldType.INPUT;
            tfInput.text = "world";
        }

        private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField {
            var result:TextField = new TextField();
            result.x = x;
            result.y = y;
            result.width = width;
            result.height = height;
            result.background = true;
            result.border = true;
            addChild(result);
            return result;
        }
    }
}

useRichTextClipboard

property 
useRichTextClipboard:Boolean

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9

Specifies whether to copy and paste the text formatting along with the text. When set to true, Flash Player copies and pastes formatting (such as alignment, bold, and italics) when you copy and paste between text fields. Both the origin and destination text fields for the copy and paste procedure must have useRichTextClipboard set to true. The default value is false.



Implementation
    public function get useRichTextClipboard():Boolean
    public function set useRichTextClipboard(value:Boolean):void

Example  ( How to use this example )
This example creates an input text field (tf1) and two dynamic text fields (tf2 and tf3). The code assigns each dynamic text field a TextFormat object (Courier Bold font). The tf2 text field has useRichTextClipboard property set to false. The tf3 text field has the useRichTextClipboard property set to true. When you copy the text from the tf2 text field and paste it into the tf1 text field, the pasted text does not include the formatting. When you copy the text from the tf3 text field (which has useRichTextClipboard set to true) and paste it into the tf1 text field, the pasted text includes the formatting.

package
{
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFieldType;
    import flash.text.TextFormat;

    public class useRichTextClipboard extends Sprite
    {
        public function useRichTextClipboard()
        {
    var format1:TextFormat = new TextFormat();
    format1.font="Courier";
    format1.bold=true;

    var tf1:TextField = createCustomTextField(10, 10, 200, 20);
    tf1.type=TextFieldType.INPUT;
    tf1.useRichTextClipboard=true;

    var tf2:TextField = createCustomTextField(220, 10, 200, 20);
    tf2.text="1.Text loses format";
    tf2.setTextFormat(format1);
    tf2.useRichTextClipboard=false;

    var tf3:TextField = createCustomTextField(220, 50, 200, 20);
    tf3.text="2.Text includes format";
    tf3.setTextFormat(format1);
    tf3.useRichTextClipboard=true;
        }

        private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField 
       {
            var result:TextField = new TextField();
            result.x = x;
            result.y = y;
            result.width = width;
            result.height = height;
            result.background = true;
            result.border = true;
            addChild(result);
            return result;
        }
    }
}

wordWrap

property 
wordWrap:Boolean

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

A Boolean value that indicates whether the text field has word wrap. If the value of wordWrap is true, the text field has word wrap; if the value is false, the text field does not have word wrap. The default value is false.



Implementation
    public function get wordWrap():Boolean
    public function set wordWrap(value:Boolean):void

Example  ( How to use this example )
This example demonstrates the difference between setting the wordWrap property to true and setting it to false. Two TextField instances are created whose contents are too large for their widths. The wordWrap property of the first (named tfWrap) is set to true; it is set to false for the second (tfNoWrap).

package {
    import flash.display.Sprite;
    import flash.text.TextField;

    public class TextField_wordWrap extends Sprite {
        public function TextField_wordWrap() {
            var tfWrap:TextField = createCustomTextField(10, 10, 100, 100);
            tfWrap.wordWrap = true;
            tfWrap.text = "(wordWrap = true):\nThis is very long text that will certainly extend beyond the width of this text field";

            var tfNoWrap:TextField = createCustomTextField(10, 150, 100, 100);
            tfNoWrap.wordWrap = false;
            tfNoWrap.text = "(wordWrap = false):\nThis is very long text that will certainly extend beyond the width of this text field";
        }

        private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField {
            var result:TextField = new TextField();
            result.x = x;
            result.y = y;
            result.width = width;
            result.height = height;
            result.background = true;
            result.border = true;
            addChild(result);
            return result;
        }
    }
}
Constructor Detail

TextField

()Constructor
public function TextField()

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Creates a new TextField instance. After you create the TextField instance, call the addChild() or addChildAt() method of the parent DisplayObjectContainer object to add the TextField instance to the display list.

The default size for a text field is 100 x 100 pixels.


Example  ( How to use this example )

The following example shows how you can dynamically create an input TextField object in ActionScript 3.0 by setting the text field object's type property to the TextFieldType.INPUT constant. Example provided by ActionScriptExamples.com.
var theTextField:TextField = new TextField();
theTextField.type = TextFieldType.INPUT;
theTextField.border = true;
theTextField.x = 10;
theTextField.y = 10;
theTextField.multiline = true;
theTextField.wordWrap = true;
addChild(theTextField);
Method Detail

appendText

()method
public function appendText(newText:String):void

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Appends the string specified by the newText parameter to the end of the text of the text field. This method is more efficient than an addition assignment (+=) on a text property (such as someTextField.text += moreText), particularly for a text field that contains a significant amount of content.

Parameters

newText:String — The string to append to the existing text.


Example  ( How to use this example )

The following example displays the time if it's not the weekend or the text, "It's the weekend," if it is. It also counts the number of characters up to a certain position and the number of lines in the text field.

The outputText text field is set to automatically fit the text and to resize as a left-justified text using autoSize property. The outputText.text property writes the first line of the content and the method appendText() appends the rest of the content. (It is not necessary to start with the text property. The appendText() method could also be used to append text from the outset.) Setting the text property a second time will overwrite the original text. Use += operator to append content with the text property.

The if statement checks if the date is Saturday (6) or Sunday (0). If it's not, the toLocaleTimeString() method returns the local time, which is appended to the text field's content.

The text field's length property is used to read the number of characters until right before the function is called, and the property numLines is used to count the number of lines in the text field. Note that the empty lines are counted in the number of lines and the empty spaces and line breaks (\n) are counted in determining the content length.

  package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
 
    public class TextField_appendTextExample extends Sprite {
         
        public function TextField_appendTextExample() {
            var outputText:TextField = new TextField();
            var today:Date = new Date();
                
            outputText.x = 10;
            outputText.y = 10;
            outputText.background = true;
            outputText.autoSize = TextFieldAutoSize.LEFT;
 
            outputText.text = "WHAT TIME IS IT?" + "\n\n";
 
            if((today.day == 0) || (today.day == 6)) {
                outputText.appendText("It's the weekend.");
                outputText.appendText("\n\n");
           
            } else {
                outputText.appendText("The time is: ");
                outputText.appendText(today.toLocaleTimeString() + ".\n\n");  
            }

            outputText.appendText("Number of characters including line breaks and spaces so far: ");
            outputText.appendText(outputText.length.toString() + "\n");
            outputText.appendText("Number of lines in the outputText: ");
            outputText.appendText(outputText.numLines.toString());   

            this.addChild(outputText);
        }
    }
}

getCharBoundaries

()method 
public function getCharBoundaries(charIndex:int):Rectangle

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Returns a rectangle that is the bounding box of the character.

Parameters

charIndex:int — The zero-based index value for the character (for example, the first position is 0, the second position is 1, and so on).

Returns
Rectangle — A rectangle with x and y minimum and maximum values defining the bounding box of the character.

See also


Example  ( How to use this example )

In the following example the getCharBoundaries() method is used to mark (put a spotlight on) a character that is selected by the user.

The class defines the spotlight Shape object that will be used to draw a rectangle around each character that is selected. When the user clicks on the myTextField text field, the clickHandler() method is invoked.

In the clickHandler() method, the getCharIndexAtPoint() method gets the clicked character's index based on the localX and localY coordinates of the mouse click, which is relative to the containing Sprite. The getCharIndexAtPoint() method returns -1 if the point (mouse click) was not over any character. Since the text field could be larger than the text, the returned integer (index) is checked to make sure the user has clicked on a character. The index integer is also used by getCharBoundaries() to get a Rectangle object that holds the boundary of the character. The clear() method clears any previously displayed spotlight Shape object. A new rectangle the size of the character's width and height boundaries is produced at the location of the character (offset from the (10, 10) coordinates) using the returned frame rectangle's x and y coordinates. To put the spotlight on the character, the spotlight Shape object is filled with color yellow and the opacity is set to 35 percent, so the character can be seen. Note that spaces are also considered a character.

package {
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.text.TextField;
    import flash.geom.Rectangle;
    import flash.events.MouseEvent;
    import flash.text.TextFieldAutoSize;
    import flash.display.Shape;

    public class TextField_getCharBoundariesExample extends Sprite
    {
        private var myTextField:TextField = new TextField();    
        private var spotlight:Shape = new Shape();
        
        public function TextField_getCharBoundariesExample() {
            
            myTextField.x = 10;
            myTextField.y = 10; 
            myTextField.border = true;
            myTextField.selectable = false;
            myTextField.autoSize = TextFieldAutoSize.LEFT;
            
            myTextField.text = "Selected a character from this text by clicking on it."

            myTextField.addEventListener(MouseEvent.CLICK, clickHandler);
            
            this.addChild(myTextField);    
            this.addChild(spotlight);
         }

        private function clickHandler (e:MouseEvent):void {
            var index:int = myTextField.getCharIndexAtPoint(e.localX, e.localY);
 
            if (index != -1) {
                 var frame:Rectangle = myTextField.getCharBoundaries(index);

                spotlight.graphics.clear();    
                spotlight.graphics.beginFill(0xFFFF00, .35);
                spotlight.graphics.drawRect((frame.x + 10), (frame.y + 10), frame.width, frame.height);            
                spotlight.graphics.endFill();
            }
        } 
    }
}

getCharIndexAtPoint

()method 
public function getCharIndexAtPoint(x:Number, y:Number):int

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Returns the zero-based index value of the character at the point specified by the x and y parameters.

Parameters

x:Number — The x coordinate of the character.
 
y:Number — The y coordinate of the character.

Returns
int — The zero-based index value of the character (for example, the first position is 0, the second position is 1, and so on). Returns -1 if the point is not over any character.

Example  ( How to use this example )

In the following example, when a user clicked on a character, the character is echoed in another text field above the text.

The first text field holds the text the user is going to select. In order to make sure the text is clicked but not selected, selectable property is set to false. When the user clicks on the firstTextField text field, the clickHandler() method is invoked.

In the clickHandler() method, the getCharIndexAtPoint() method returns the character's index based on the localX and localY coordinates of the mouse click. Since the text field could be larger than the text, the return integer (index) is checked to make sure the user has clicked on a character. (The getCharIndexAtPoint() method returns -1, if the point (mouse click) was not over a character.) The mouse coordinates is used to set the coordinates of the new text field where the echoed character will appear. The color of the character in the second text field is set to red. Finally the text of the second field is set to the selected character, which is retrieved using the charAt() method. Note that using the text property instead of the appendText() method will overwrite the character in the second text field, instead of appending it.

package {
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.text.TextField;
    import flash.geom.Rectangle;
    import flash.events.MouseEvent;
    import flash.text.TextFieldAutoSize;
    
    public class TextField_getCharIndexAtPointExample extends Sprite {
        private var firstTextField:TextField = new TextField();    
        private var secondTextField:TextField = new TextField();
        
        public function TextField_getCharIndexAtPointExample() {

            firstTextField.x = 100;
            firstTextField.y = 100; 
            firstTextField.width = 260;
            firstTextField.height = 20;
            firstTextField.border = true;
            firstTextField.background = true;
            firstTextField.selectable = false;
            
            firstTextField.text = "Selected a character from this text by clicking on it."

            firstTextField.addEventListener(MouseEvent.CLICK, clickHandler);

            this.addChild(firstTextField);    
            this.addChild(secondTextField);
         }

        private function clickHandler (e:MouseEvent):void {
            var index:int = firstTextField.getCharIndexAtPoint(e.localX, e.localY);

            if (index != -1) {
                secondTextField.x = mouseX;
                secondTextField.y =  70;
                secondTextField.border = true;
                secondTextField.selectable = false;
                secondTextField.background = true;
                secondTextField.textColor = 0xFF0000;
                secondTextField.autoSize = TextFieldAutoSize.LEFT;
                secondTextField.text = firstTextField.text.charAt(index);    
            }
        } 
    }
}

getFirstCharInParagraph

()method 
public function getFirstCharInParagraph(charIndex:int):int

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Given a character index, returns the index of the first character in the same paragraph.

Parameters

charIndex:int — The zero-based index value of the character (for example, the first character is 0, the second character is 1, and so on).

Returns
int — The zero-based index value of the first character in the same paragraph.

Throws
RangeError — The character index specified is out of range.

Example  ( How to use this example )

In the following example, paragraph formatting is applied to the text field content. When the user clicks on a paragraph, the text of the paragraph will be aligned right and when the user clicks on the paragraph again, it will return to the original (default) format (left-align).

In the constructor, the myTextField text field is set to text wrap. The getTextFormat method returns the original format of the first character of the content of the text field, which is placed in the originalFormat TextFormat object. A new TextFormat object (newFormat) is also defined and its align property is assigned to right-justified. When the user clicks on the text field, the clickHandler() method is invoked.

In the clickHandler() method, the getCharIndexAtPoint() method returns the character's index based on the localX and localY coordinates of the mouse click. The first if statement checks to see if the use has clicked on a character. Using the clickIndex integer returned by the getCharIndexAtPoint() method, the getFirstCharInParagraph() method returns the index of the first character in the paragraph the user has clicked. The index of the last character in the paragraph is determined by adding the length of the paragraph (using getParagraphLength() method) to the index of the first character in the paragraph, minus the last character (\n). The second if statement checks the format of the first character in the paragraph. If its alignment value is the same as the original format (left-justified), the new format is applied to all the characters in the paragraph. Otherwise, the format of the paragraph is set back to the original format. Alignment, along with formatting like indent, bullet, tab stop, left and right margin are formats that are meant for paragraphs. Note that once word wrap or line break is used, the formatting will only apply to the first line of the paragraph if endIndex argument is not defined for the setTextFormat() method.

package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.events.MouseEvent;
    import flash.text.TextFormat;
    import flash.text.TextFormatAlign;

    public class TextField_getFirstCharInParagraphExample extends Sprite
    {
        private var myTextField:TextField = new TextField();
        private var originalFormat:TextFormat = new TextFormat();
        private var newFormat:TextFormat = new TextFormat(); 
        
        public function TextField_getFirstCharInParagraphExample() {
            myTextField.x = 10;
            myTextField.y = 10; 
            myTextField.border = true;
            myTextField.wordWrap = true;
            myTextField.width = 300;
            myTextField.height = 300; 
            myTextField.background = true;
             
            myTextField.appendText("The TextField class is used to create display objects for "
                        + "text display and input. All dynamic and input text fields in a SWF file " 
                        + "are instances of the TextField class. You can use the TextField class "
                        + "to perform low-level text rendering. However, in Flex, you typically use "
                        + "the Label, Text, TextArea, and TextInput controls to process text. "  
                        + "You can give a text field an instance name in the Property inspector "
                        + "and use the methods and properties of the TextField class to manipulate it with ActionScript. "
                        + "TextField instance names are displayed in the Movie Explorer and in the Insert "
                        + "Target Path dialog box in the Actions panel.\n\n"  
                        + "To create a text field dynamically, use the TextField constructor.\n\n"
                        + "The methods of the TextField class let you set, select, and manipulate "  
                        + "text in a dynamic or input text field that you create during authoring or at runtime.\n\n");

            originalFormat = myTextField.getTextFormat(0);

            newFormat.align = TextFormatAlign.RIGHT;

            myTextField.addEventListener(MouseEvent.CLICK, clickHandler);
  
            this.addChild(myTextField);
        }

        private function clickHandler(e:MouseEvent):void {
            var clickIndex:int = myTextField.getCharIndexAtPoint(e.localX, e.localY);
                  
            if(clickIndex != -1) {
                var paragraphFirstIndex:int = myTextField.getFirstCharInParagraph(clickIndex);
                var paragraphEndIndex:int = paragraphFirstIndex + ((myTextField.getParagraphLength(clickIndex) - 1));
            
                if (myTextField.getTextFormat(paragraphFirstIndex).align == originalFormat.align) {
                     myTextField.setTextFormat(newFormat, paragraphFirstIndex, paragraphEndIndex);
                }else {
                     myTextField.setTextFormat(originalFormat, paragraphFirstIndex, paragraphEndIndex);
                }
            } 
        }
    }
}
 

getImageReference

()method 
public function getImageReference(id:String):DisplayObject

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Returns a DisplayObject reference for the given id, for an image or SWF file that has been added to an HTML-formatted text field by using an <img> tag. The <img> tag is in the following format:

   <img src = 'filename.jpg' id = 'instanceName' >

Parameters

id:String — The id to match (in the id attribute of the <img> tag).

Returns
DisplayObject — The display object corresponding to the image or SWF file with the matching id attribute in the <img> tag of the text field. For media loaded from an external source, this object is a Loader object, and, once loaded, the media object is a child of that Loader object. For media embedded in the SWF file, it is the loaded object. If no <img> tag with the matching id exists, the method returns null.

See also


Example  ( How to use this example )

In the following example, when the text field is clicked, the image in the field is set to 25 percent opacity and it rotates 90 degrees from its original rotation. The image will continue to rotate with each subsequent click.

The image (image.jpg) is included via the HTML. (Here it is assumed that an image file is in the same directory as the SWF file.) An id attribute needs to be defined for the img tag in order to access the image using getImageReference() method. The htmlText property is used to include HTML-formatted string content. When the user clicks on the myTextField text field, the clickHandler() method is invoked.

In the clickHandler() method, the getImageReference() method returns a reference to the image as a DisplayObject. This reference can be used to manipulate the image, like any DisplayObject object. Here, the alpha (transparency) and rotation properties are set. The transform property can also be used to access the display object's matrix, color transform, and pixel bounds. Note also that flash.display.DisplayObject needs to be imported.

package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.display.DisplayObject;
    
    import flash.text.TextFieldAutoSize;
    
    public class TextField_getImageReferenceExample extends Sprite
    {
        private var myTextField:TextField = new TextField();
        
        public function TextField_getImageReferenceExample()
        {
            var myText1:String = "<p>Here is an image we want to mainpulate: <img src='image.jpg' id='testimage'></p>";

            myTextField.x = 10;
            myTextField.y = 10;
            myTextField.width = 250;
            myTextField.height = 250;
            myTextField.background = true;
            myTextField.border = true;
            myTextField.border = true;
            myTextField.multiline = true;

            myTextField.htmlText = myText1;
            
            myTextField.addEventListener(MouseEvent.CLICK, clickHandler);
            
            this.addChild(myTextField);
        }
 
        private function clickHandler(e:MouseEvent):void {
            var imageRef:DisplayObject = myTextField.getImageReference("testimage");
 
            imageRef.rotation += 90;
            imageRef.x = 125;
            imageRef.y = 125;
            imageRef.alpha = 0.25;      
        }
    }
}

getLineIndexAtPoint

()method 
public function getLineIndexAtPoint(x:Number, y:Number):int

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Returns the zero-based index value of the line at the point specified by the x and y parameters.

Parameters

x:Number — The x coordinate of the line.
 
y:Number — The y coordinate of the line.

Returns
int — The zero-based index value of the line (for example, the first line is 0, the second line is 1, and so on). Returns -1 if the point is not over any line.

Example  ( How to use this example )

In the following example, when a user selects a line from the Shakespeare's sonnet, it is copied (appended) into a new text field.

In the constructor, the poem text field is set not to wrap (since it's a poem). The autoSize property also is used to set the text to automatically fit and to have it resize as a left-justified text. The poemCopy text field is placed under the poem text field. When a user clicks on some line of the poem, the clickHandler() method is invoked.

In clickHandler() method, the getLineIndexAtPoint() method returns the line index of where the user has clicked based on the localX and localY coordinates of the mouse click. (Since the original poem fits the size of the text field here, it is not necessary to check for out of range error (RangeError) thrown by getCharIndexAtPoint() method.) The line index is then used to get the content of the line as a string with the getLineText() method, which is then appended to the poemCopy text field content. The copying can go on continuously but after a point, the text will be outside of the range of the viewable poemCopy text field.

package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.events.MouseEvent;
    import flash.text.TextFormat;
    import flash.text.TextFieldAutoSize;

    public class TextField_getLineIndexAtPointExample extends Sprite {
        private var poem:TextField = new TextField();
        private var poemCopy:TextField = new TextField();
        
        public function TextField_getLineIndexAtPointExample() {
            poem.border = true;
            poem.autoSize = TextFieldAutoSize.LEFT;
            poem.x = 10;
            poem.wordWrap = false;

            poemCopy.height = 250;
            poemCopy.width = 270;
            poemCopy.y = 230;
            poemCopy.x = 10;
            poemCopy.background = true;
            poemCopy.border = true;
            poemCopy.wordWrap = false;
            
            poem.appendText("Let me not to the marriage of true minds\n"
                              + "Admit impediments. love is not love\n"
                              + "Which alters when it alteration finds\n"
                              + "Or bends with the remover to remove:\n"
                              + "O no! it is an ever-fixed mark\n" 
                              + "That looks on tempests and is never shaken;\n"
                              + "It is the star to every wandering bark,\n"
                              + "Whose worth's unknown, although his height be taken.\n"
                              + "Love's not Time's fool, though rosy lips and cheeks\n"
                              + "Within his bending sickle's compass come:\n"
                              + "Love alters not with his brief hours and weeks,\n"
                              + "But bears it out even to the edge of doom.\n"
                              + "If this be error and upon me proved,\n"
                              + "I never writ, nor no man ever loved.");

           poem.addEventListener(MouseEvent.CLICK, clickHandler); 

           this.addChild(poem); 
           this.addChild(poemCopy);
        }
    
        private function clickHandler(e:MouseEvent):void {
                var index:int = poem.getLineIndexAtPoint(e.localX, e.localY);
                var s:String;

                s = poem.getLineText(index);
                poemCopy.appendText(s + "\n");
        }
    }
}

getLineIndexOfChar

()method 
public function getLineIndexOfChar(charIndex:int):int

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Returns the zero-based index value of the line containing the character specified by the charIndex parameter.

Parameters

charIndex:int — The zero-based index value of the character (for example, the first character is 0, the second character is 1, and so on).

Returns
int — The zero-based index value of the line.

Throws
RangeError — The character index specified is out of range.

Example  ( How to use this example )

In the following example, the getLineIndexOfChar() method returns the line numbers for the 100th and 500th characters in the text field.

The myTextField text field is defined to wrap and resize as a left-justified text. The getLineIndexOfChar() method returns the line index for the specified character indexes (100 and 500). This information is then appended after the paragraph. Note that since line index begins with 0, the line index (index) is increased by 1 to get the line number. Also if the display is resized the line number may change but the information here will stay the same since the method is only invoked once.

package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;

    public class TextField_getLineIndexOfCharExample extends Sprite 
    {
        public function TextField_getLineIndexOfCharExample()
        {
            var myTextField:TextField = new TextField();
            
            myTextField.x = 10;
            myTextField.y = 10;
            myTextField.width = 200;
            myTextField.background = true;  
            myTextField.border = true;
            myTextField.wordWrap = true;
            myTextField.autoSize = TextFieldAutoSize.LEFT;

            myTextField.appendText("The TextField class is used to create display objects for "
                + "text display and input. All dynamic and input text fields in a SWF file" 
                + "are instances of the TextField class. You can use the TextField class "
                + "to perform low-level text rendering. However, in Flex, you typically use "
                + "the Label, Text, TextArea, and TextInput controls to process text. "  
                + "You can give a text field an instance name in the Property inspector "
                + "and use the methods and properties of the TextField class to manipulate it with ActionScript. "
                + "TextField instance names are displayed in the Movie Explorer and in the Insert "
                + "Target Path dialog box in the Actions panel.\n\n");

            var index:int = myTextField.getLineIndexOfChar(100);
            myTextField.appendText("100th character is in line: " +  (index + 1) + "\n");
            index = myTextField.getLineIndexOfChar(500);
            myTextField.appendText("500th character is in line: " + (index + 1));

            this.addChild(myTextField);
        }
    }
}

getLineLength

()method 
public function getLineLength(lineIndex:int):int

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Returns the number of characters in a specific text line.

Parameters

lineIndex:int — The line number for which you want the length.

Returns
int — The number of characters in the line.

Throws
RangeError — The line number specified is out of range.

Example  ( How to use this example )

In the following example, once the user selects a line, its line length (number of characters) is displayed in a separate text field.

As an illustration, myTextField text field, which displays the text that will be counted, is set to INPUT, meaning users can actually change the lines or add lines between the lines or at the end. (There is an empty line created by using line break (\n) at the end of the last line.) The countLines text field, where the result of counting the line length is displayed, is set below myTextField text field and its text is not selectable. When the user clicks on a line in the myTextField text field, the clickHandler() method is invoked.

In the clickHandler() method, the getLineIndexAtPoint() method returns the line index of where the user clicked, by using the localX and localY coordinates of the mouse click. The if statement checks to see if the use has clicked on a character. If so, the getLineLength() method, using the index of line, returns the number of characters in the line. Note that the empty lines between the lines include the second line break (\n) and have a count of 1 character, while the line after the last line has a 0 count. Spaces also count as one character. The users can write a new line or changes a line and get the character count of the line by clicking on it. If text wrap is used and the screen is resized, the line index could change.

 package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFieldType;
    import flash.events.Event;
    import flash.events.MouseEvent;

    public class TextField_getLineLengthExample extends Sprite {
        private var myTextField:TextField = new TextField();
        private var countLines:TextField = new TextField();  

        public function TextField_getLineLengthExample() {
            myTextField.x = 10;
            myTextField.y = 10;
            myTextField.width = 350;
            myTextField.height = 150;
            myTextField.background = true;
            myTextField.border = true;
            myTextField.type = TextFieldType.INPUT;
            
            myTextField.appendText("Click on the lines to count its number of characters:\n\n");
            myTextField.appendText("This is a short line.\n");
            myTextField.appendText("This is a longer line than the last line.\n\n");
            myTextField.appendText("This one is even longer than the one before. It has two sentences.\n");

            this.addChild(myTextField);

            countLines.border = true;
            countLines.x = 10;
            countLines.y = 180;
            countLines.height = 30;
            countLines.width = 200;
            countLines.background = true;
            countLines.selectable = false;

           this.addChild(countLines);    

            myTextField.addEventListener(MouseEvent.CLICK, clickHandler);
        }

        private function clickHandler(e:MouseEvent):void {
            var index:int = myTextField.getLineIndexAtPoint(e.localX, e.localY);
        
            if (index != -1) {
            var lenght:int = myTextField.getLineLength(index);

            countLines.text = "Number of characters in the line is: " + lenght.toString();
            }
        }
    }
}

getLineMetrics

()method 
public function getLineMetrics(lineIndex:int):flash.text:TextLineMetrics

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Returns metrics information about a given text line.

Parameters

lineIndex:int — The line number for which you want metrics information.

Returns
flash.text:TextLineMetrics — A TextLineMetrics object.

Throws
RangeError — The line number specified is out of range.

See also


Example  ( How to use this example )

The following example displays some line metrics values for two differently formatted lines of text.

The text appended is two lines from the Song of Myself by Walt Whitman. A new TextFormat object (newFormat) is used to set the format of the second line. The first line holds the default format. The getLineMetrics() method returns a TextLineMetrics object for a specific line. (Line index begins with 0.) Using metrics1 and metrics2 TextLineMetrics objects for the line one and two, respectively, the ascent, descent, height, and weight value of the line are retrieved and displayed. The result numbers are converted to string but not rounded. Note that this value is for the line and not a specific character. It reflects the range of characters for a line. For example, if a line has different characters with different height formats, the character with the highest height will determine the value. This also means that if one of the character's format is changes, some of the metrics values could also change.

package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextLineMetrics;
    import flash.text.TextFieldAutoSize;
    import flash.text.AntiAliasType;
    import flash.text.TextFormat;
 
    public class TextField_getLineMetricsExample extends Sprite {

        public function TextField_getLineMetricsExample() {
            var myTextField:TextField = new TextField();
            var newFormat:TextFormat = new TextFormat(); 

            myTextField.x = 10;
            myTextField.y = 10;
            myTextField.background = true;
            myTextField.wordWrap = false;
            myTextField.autoSize = TextFieldAutoSize.LEFT;
            
            myTextField.appendText("A child said What is the grass? fetching it to me with full hands;\n");
            myTextField.appendText("How could I answer the child? I do not know what it is any more than he.\n\n");

            newFormat.size = 14;
            newFormat.font = "Arial";
            newFormat.italic = true;
            myTextField.setTextFormat(newFormat, 67, 139);
               
            var metrics1:TextLineMetrics = myTextField.getLineMetrics(0);
             
            myTextField.appendText("Metrics ascent for the line 1 is: " + metrics1.ascent.toString() + "\n");
            myTextField.appendText("Metrics descent is: " + metrics1.descent.toString() + "\n");
            myTextField.appendText("Metrics height is: " + metrics1.height.toString() + "\n"); 
            myTextField.appendText("Metrics width is: " + metrics1.width.toString() + "\n\n");

            var metrics2:TextLineMetrics = myTextField.getLineMetrics(1);
             
            myTextField.appendText("Metrics ascent for the line 2 is: " + metrics2.ascent.toString() + "\n");
            myTextField.appendText("Metrics descent is: " + metrics2.descent.toString() + "\n");
            myTextField.appendText("Metrics height is: " + metrics2.height.toString() + "\n"); 
            myTextField.appendText("Metrics width is: " + metrics2.width.toString() + "\n");

            addChild(myTextField);
        }
    }
}

getLineOffset

()method 
public function getLineOffset(lineIndex:int):int

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Returns the character index of the first character in the line that the lineIndex parameter specifies.

Parameters

lineIndex:int — The zero-based index value of the line (for example, the first line is 0, the second line is 1, and so on).

Returns
int — The zero-based index value of the first character in the line.

Throws
RangeError — The line number specified is out of range.

Example  ( How to use this example )

The following example checks for the first character of the line 4, which will change if the screen (and the text field) is resized.

The myTextField text field is set to word wrap. The countField text field will display the first character of line 4. When the user clicks on the myTextField text field, the clickHandler() method is invoked.

In the clickHandler() method, the getLineOffset() method returns the index of the first character in the line index 3, which is the fourth line of the text. (First line has a 0 index.) The charAt() method is used to get the character using the index of the first character of the fourth line. The countField text field content is updated with this information using the text property of the countField text field. Using the countField.text property means that each time after the click the content of the countField text field will be overwritten. If the user resizes the display, the content will wrap and the first character of the line 4 could change. By clicking again on the myTextField field, the content of countField text field is updated with the new first character for the fourth line.

package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.events.MouseEvent;

    public class TextField_getLineOffsetExample extends Sprite {
        private var myTextField:TextField = new TextField();
        private var countField:TextField = new TextField();
        
        public function TextField_getLineOffsetExample() {
            myTextField.x = 10;
            myTextField.y = 10;
            myTextField.width = 150;
            myTextField.height = 300;
            myTextField.background = true;
            myTextField.border = true;
            myTextField.wordWrap = true;

            countField.height = 20;
            countField.width = 200;
            countField.x = 10;
            countField.y = 320;
            countField.selectable = false;
            
            myTextField.appendText("The TextField class is used to create display objects for "
                        + "text display and input. All dynamic and input text fields in a SWF file " 
                        + "are instances of the TextField class. You can use the TextField class "
                        + "to perform low-level text rendering. However, in Flex, you typically use "
                        + "the Label, Text, TextArea, and TextInput controls to process text. "  
                        + "You can give a text field an instance name in the Property inspector "
                        + "and use the methods and properties of the TextField class to manipulate it with ActionScript.");

            myTextField.addEventListener(MouseEvent.CLICK, clickHandler);
        
            this.addChild(myTextField);
            this.addChild(countField);
        }
    
            private function clickHandler(e:MouseEvent):void {
                var c:String;
                var index:int;
                
                index = myTextField.getLineOffset(3);
                c = myTextField.text.charAt(index);
                countField.text = "The first character of line 4 is: " + c;
            }
    }
}

getLineText

()method 
public function getLineText(lineIndex:int):String

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Returns the text of the line specified by the lineIndex parameter.

Parameters

lineIndex:int — The zero-based index value of the line (for example, the first line is 0, the second line is 1, and so on).

Returns
String — The text string contained in the specified line.

Throws
RangeError — The line number specified is out of range.

Example  ( How to use this example )

In the following example, the line numbers of all the instances of the word "love" used in Shakespeare's sonnet are found and displayed.

The poem text field is set to fit automatically the text and to resize as a left-justified text. The wordWrap property is set to false, so the lines of the poem would not wrap, though normally when using the autoSize property, this should not be a problem. The for loop iterates through the lines of the sonnet using the property numLines of the text field. The getLineText() method returns the content of the line as a string. (Note that the numLines property returns the number of lines starting with line 1, while for the getLineText() method the line number begins with 0.) Using the regular expression pattern (/love/i), the if statement looks for any substring of the word in upper or lowercase. If the pattern is found, the search method returns the index of the first matching substring, otherwise it returns -1 (if there is no match). The line number where "love" was found ((i + 1)) is then placed in the string lineResult. The string method converts the number argument ((i + 1)) to a string as long as there is another argument that is a string (" "). The line result of the search will include lines with the words "loved" or "Love's." If the string "Love was found in lines:" was appended before the for loop, the word "Love" in this line would also have been included.

package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.utils.Timer;
    import flash.events.TimerEvent;
 
    public class TextField_getLineTextExample extends Sprite {
           
        public function TextField_getLineTextExample() {
           var poem:TextField = new TextField();
           var lineResult:String = ""; 
           var pattern:RegExp = /love/i;

            poem.x = 10;
            poem.y = 10;
            poem.background = true;
            poem.wordWrap = false;
            poem.autoSize = TextFieldAutoSize.LEFT;
            
            poem.text = "Let me not to the marriage of true minds\n"
                              + "Admit impediments. love is not love\n"
                              + "Which alters when it alteration finds\n"
                              + "Or bends with the remover to remove:\n"
                              + "O no! it is an ever-fixed mark\n" 
                              + "That looks on tempests and is never shaken;\n"
                              + "It is the star to every wandering bark,\n"
                              + "Whose worth's unknown, although his height be taken.\n"
                              + "Love's not Time's fool, though rosy lips and cheeks\n"
                              + "Within his bending sickle's compass come:\n"
                              + "Love alters not with his brief hours and weeks,\n"
                              + "But bears it out even to the edge of doom.\n"
                              + "If this be error and upon me proved,\n"
                              + "I never writ, nor no man ever loved.\n\n";

            for (var i:int = 0; i < poem.numLines; i++) {

                var s:String = poem.getLineText(i);
                        
                if(s.search(pattern) != -1) {
                    lineResult += (i + 1) + " ";
                }
            }

            poem.appendText("Love was found in lines: " + lineResult);
             
            this.addChild(poem);                      
        }
    }
}

getParagraphLength

()method 
public function getParagraphLength(charIndex:int):int

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Given a character index, returns the length of the paragraph containing the given character. The length is relative to the first character in the paragraph (as returned by getFirstCharInParagraph()), not to the character index passed in.

Parameters

charIndex:int — The zero-based index value of the character (for example, the first character is 0, the second character is 1, and so on).

Returns
int — Returns the number of characters in the paragraph.

Throws
RangeError — The character index specified is out of range.

See also


Example  ( How to use this example )

In the following example, when a user selects a paragraph, the paragraph's length and number of "s" characters in the paragraph are displayed in a separate text field.

The myTextField text field displays the paragraphs that the user will select. When the user click on the text field, the MouseEvent.CLICK event is dispatched, and the clickHandler() method is called. The paragraph length and number of "s" characters will appear in countField text field, which is placed below myTextField text field.

In the clickHandler() method, the getCharIndexAtPoint() method returns the character's index based on the localX and localY coordinates of the mouse click. The first if statement checks to see if the use has clicked on a character. The getFirstCharInParagraph() method, uses this index to return the index of the first character in the same paragraph. The paragraph length returned by getParagraphLength() method is used with the index of the first character in the paragraph to determine the index for the end of the paragraph. A for loop iterates through the paragraph looking for the number of "s" characters.

package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.events.MouseEvent;

    public class TextField_getParagraphLengthExample extends Sprite {
        private var myTextField:TextField = new TextField();
        private var countField:TextField = new TextField();

        public function TextField_getParagraphLengthExample() {
            myTextField.x = 10;
            myTextField.y = 10;
            myTextField.background = true;
            myTextField.border = true;
            myTextField.wordWrap = true;
            myTextField.width = 300;
            myTextField.height = 280;
            
            myTextField.appendText("The TextField class is used to create display objects for "
                        + "text display and input. All dynamic and input text fields in a SWF file" 
                        + "are instances of the TextField class. You can use the TextField class "
                        + "to perform low-level text rendering. However, in Flex, you typically use "
                        + "the Label, Text, TextArea, and TextInput controls to process text. "  
                        + "You can give a text field an instance name in the Property inspector "
                        + "and use the methods and properties of the TextField class to manipulate it with ActionScript. "
                        + "TextField instance names are displayed in the Movie Explorer and in the Insert "
                        + "Target Path dialog box in the Actions panel.\n\n"  
                        + "To create a text field dynamically, use the TextField() constructor.\n\n"
                        + "The methods of the TextField class let you set, select, and manipulate "  
                        + "text in a dynamic or input text field that you create during authoring or at runtime.");

            myTextField.addEventListener(MouseEvent.CLICK, clickHandler);
            
            countField.x = 10;
            countField.y = 300;
            countField.height = 50;
            countField.width = 250;
            countField.background = true;
            countField.selectable = false;

            this.addChild(myTextField);
            this.addChild(countField);
        }

        private function clickHandler(e:MouseEvent):void {
            var index:int = myTextField.getCharIndexAtPoint(e.localX, e.localY);
            
            if(index != -1) {
                var beginParag:int = myTextField.getFirstCharInParagraph(index);
                var paragLength:int = myTextField.getParagraphLength(index);
                var endParag:int = beginParag + paragLength;
                var sCount:uint = 0;

                for (var i:int = beginParag; i <= endParag; i++) {
                    if ((myTextField.text.charAt(i) == "s") || (myTextField.text.charAt(i) == "S")) {
                        sCount++; 
                    }

                countField.text = "Paragraph length is: " + paragLength.toString() + "\n" 
                        + "Number of 's' characters in the paragraph: " + sCount.toString();
                }
            }
        }
    }
}

getTextFormat

()method 
public function getTextFormat(beginIndex:int = -1, endIndex:int = -1):flash.text:TextFormat

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Returns a TextFormat object that contains formatting information for the range of text that the beginIndex and endIndex parameters specify. Only properties that are common to the entire text specified are set in the resulting TextFormat object. Any property that is mixed, meaning that it has different values at different points in the text, has a value of null.

If you do not specify values for these parameters, this method is applied to all the text in the text field.

The following table describes three possible usages:

UsageDescription
my_textField.getTextFormat()Returns a TextFormat object containing formatting information for all text in a text field. Only properties that are common to all text in the text field are set in the resulting TextFormat object. Any property that is mixed, meaning that it has different values at different points in the text, has a value of null.
my_textField.getTextFormat(beginIndex:Number)Returns a TextFormat object containing a copy of the text format of the character at the beginIndex position.
my_textField.getTextFormat(beginIndex:Number,endIndex:Number)Returns a TextFormat object containing formatting information for the span of text from beginIndex to endIndex-1. Only properties that are common to all of the text in the specified range are set in the resulting TextFormat object. Any property that is mixed (that is, has different values at different points in the range) has its value set to null.

Parameters

beginIndex:int (default = -1) — Optional; an integer that specifies the starting location of a range of text within the text field.
 
endIndex:int (default = -1) — Optional; an integer that specifies the position of the first character after the desired text span. As designed, if you specify beginIndex and endIndex values, the text from beginIndex to endIndex-1 is read.

Returns
flash.text:TextFormat — The TextFormat object that represents the formatting properties for the specified text.

Throws
RangeError — The beginIndex or endIndex specified is out of range.

See also


Example
How to use this example
Please see the getFirstCharInParagraph() or setTextFormat() method example for illustrations of how to use the getTextFormat() method.

isFontCompatible

()method 
public static function isFontCompatible(fontName:String, fontStyle:String):Boolean

Language Version: ActionScript 3.0
Runtime Versions: Flash Player 10, AIR 1.5, Flash Lite 4

Returns true if an embedded font is available with the specified fontName and fontStyle where Font.fontType is flash.text.FontType.EMBEDDED. Starting with Flash Player 10, two kinds of embedded fonts can appear in a SWF file. Normal embedded fonts are only used with TextField objects. CFF embedded fonts are only used with the flash.text.engine classes. The two types are distinguished by the fontType property of the Font class, as returned by the enumerateFonts() function.

TextField cannot use a font of type EMBEDDED_CFF. If embedFonts is set to true and the only font available at run time with the specified name and style is of type EMBEDDED_CFF, Flash Player fails to render the text, as if no embedded font were available with the specified name and style.

If both EMBEDDED and EMBEDDED_CFF fonts are available with the same name and style, the EMBEDDED font is selected and text renders with the EMBEDDED font.

Parameters

fontName:String — The name of the embedded font to check.
 
fontStyle:String — Specifies the font style to check. Use flash.text.FontStyle

Returns
Booleantrue if a compatible embedded font is available, otherwise false.

Throws
ArgumentError — The fontStyle specified is not a member of flash.text.FontStyle.

See also

replaceSelectedText

()method 
public function replaceSelectedText(value:String):void

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Replaces the current selection with the contents of the value parameter. The text is inserted at the position of the current selection, using the current default character format and default paragraph format. The text is not treated as HTML.

You can use the replaceSelectedText() method to insert and delete text without disrupting the character and paragraph formatting of the rest of the text.

Note: This method does not work if a style sheet is applied to the text field.

Parameters

value:String — The string to replace the currently selected text.


Throws
Error — This method cannot be used on a text field with a style sheet.

See also


Example  ( How to use this example )

In the following example, the user erases some text from the first text field by selecting it and replaces a selected text in the second text field with "NEW TEXT" string.

Two different TextField objects are created and event listeners are added for the MouseEvent.MOUSE_UP events. Mouse up occurs when the user releases the mouse, an event that normally happens after a selection of text is made. Note that the default setting for a text field is for its text to be selected.

In the mouseHandler1() method, when a user release a mouse in the myTextField1 text field, the text is erased by replacing it with an empty string. This can continue until all the text is erased. In the mouseHandler2() method, when a user selects some text in myTextField2 text field, properties selectionBeginIndex and selectionEndIndex are checked to see if any character was selected. (The selectionBeginIndex and selectionEndIndex properties don't have the same value if some text were selected.) The selected text is then replaced with "NEW TEXT" string. This can continue until all the original text of the second text field is replaced with the "NEW TEXT" string.

package {
    import flash.display.Sprite;
    import flash.text.TextField;    
    import flash.events.MouseEvent;

    public class TextField_replaceSelectedTextExample extends Sprite {
        private var myTextField1:TextField = new TextField();
        private var myTextField2:TextField = new TextField();
        
        public function TextField_replaceSelectedTextExample() {
            myTextField1.x = 10;
            myTextField1.width = 300;
            myTextField1.height = 50; 
            myTextField1.background = true; 
            myTextField1.border = true;
            myTextField1.text = "Select the text you want to remove from the line.";
            
            myTextField2.x = 10;
            myTextField2.y = 60;
            myTextField2.width = 300;
            myTextField2.height = 50;
            myTextField2.background = true;
            myTextField2.border = true;
            myTextField2.text = "Select the text you want to replace with NEW TEXT.";
            
            myTextField1.addEventListener(MouseEvent.MOUSE_UP, mouseHandler1);
            myTextField2.addEventListener(MouseEvent.MOUSE_UP, mouseHandler2);
            
            this.addChild(myTextField1);
            this.addChild(myTextField2);
        }
        
        private function mouseHandler1(e:MouseEvent):void {
            myTextField1.replaceSelectedText("");
        }

        private function mouseHandler2(e:MouseEvent):void {
            if(myTextField2.selectionBeginIndex != myTextField2.selectionEndIndex) {
                myTextField2.replaceSelectedText("NEW TEXT");    
            }
        }
    }
}

replaceText

()method 
public function replaceText(beginIndex:int, endIndex:int, newText:String):void

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Replaces the range of characters that the beginIndex and endIndex parameters specify with the contents of the newText parameter. As designed, the text from beginIndex to endIndex-1 is replaced.

Note: This method does not work if a style sheet is applied to the text field.

Parameters

beginIndex:int — The zero-based index value for the start position of the replacement range.
 
endIndex:int — The zero-based index position of the first character after the desired text span.
 
newText:String — The text to use to replace the specified range of characters.


Throws
Error — This method cannot be used on a text field with a style sheet.

Example  ( How to use this example )

The following example uses the replaceText() method to delete, replace and insert some text into a text field.

The outputText text field is set to automatically fit the text and to resize as a left-justified text. With the first replaceText() method call, the first line ("This is the wrong heading") is replaced with "THIS IS THE HEADING FOR EVERYONE." With the second method call, the text "CORRECT" is inserted between "THE" and "HEADING." With the third method call, the words "FOR EVERYONE" are deleted. Note that with each call to the method appendText(), the current text's begin and end index are changed. Here, only the final text (after the changes have been made) will display.

package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    
    public class TextField_replaceTextExample extends Sprite {

        public function TextField_replaceTextExample() {
            var outputText:TextField = new TextField();

            outputText.x = 10;
            outputText.y = 10;
            outputText.background = true;
            outputText.autoSize = TextFieldAutoSize.LEFT;
            
            outputText.appendText("This is the wrong heading");
            outputText.appendText("\n\n"); 
            outputText.appendText("This is the body of the text.");

            outputText.replaceText(0, 25, "THIS IS THE HEADING FOR EVERYONE");

            outputText.replaceText(12, 12, "CORRECT ");
            
            outputText.replaceText(27, 40, "");
            
           this.addChild(outputText);
         }
    }
}

setSelection

()method 
public function setSelection(beginIndex:int, endIndex:int):void

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Sets as selected the text designated by the index values of the first and last characters, which are specified with the beginIndex and endIndex parameters. If the two parameter values are the same, this method sets the insertion point, as if you set the caretIndex property.

Parameters

beginIndex:int — The zero-based index value of the first character in the selection (for example, the first character is 0, the second character is 1, and so on).
 
endIndex:int — The zero-based index value of the last character in the selection.

See also


Example  ( How to use this example )

In the following example, when the user clicks anywhere in the text field a predefined range of text will be selected (highlighting the words "TEXT IN ALL CAPS").

Two event listeners for the myTextField text field respond to the user's mouse clicks or mouse up events. Mouse up will occur when the user releases the mouse, an event that normally happens after a selection of text is made. Note that the default setting for a text field is for its text to be selected. When some text is clicked, clickHandler() method is invoked. When some text is selected and the mouse is released, mouseUpHandler() method is invoked.

In both clickHandler() and mouseUpHandler() methods, the setSelection() method sets only the characters between indexes 54 and 70 (TEXT IN ALL CAPS) to be selected.

package {
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    
    public class TextField_setSelectionExample extends Sprite
    {
        private var myTextField:TextField = new TextField();

        public function TextField_setSelectionExample() {
            myTextField.autoSize = TextFieldAutoSize.LEFT;
            myTextField.text = "No matter where you click on this text field only the TEXT IN ALL CAPS is selected.";

            myTextField.addEventListener(MouseEvent.CLICK, clickHandler);
            myTextField.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);

            this.addChild(myTextField);
        }

        private function clickHandler(event:MouseEvent):void {
            myTextField.setSelection(54, 70);
        }

        private function mouseUpHandler(event:MouseEvent):void {
            myTextField.setSelection(54, 70);
        }

    }
}

setTextFormat

()method 
public function setTextFormat(format:flash.text:TextFormat, beginIndex:int = -1, endIndex:int = -1):void

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Applies the text formatting that the format parameter specifies to the specified text in a text field. The value of format must be a TextFormat object that specifies the desired text formatting changes. Only the non-null properties of format are applied to the text field. Any property of format that is set to null is not applied. By default, all of the properties of a newly created TextFormat object are set to null.

Note: This method does not work if a style sheet is applied to the text field.

The setTextFormat() method changes the text formatting applied to a range of characters or to the entire body of text in a text field. To apply the properties of format to all text in the text field, do not specify values for beginIndex and endIndex. To apply the properties of the format to a range of text, specify values for the beginIndex and the endIndex parameters. You can use the length property to determine the index values.

The two types of formatting information in a TextFormat object are character level formatting and paragraph level formatting. Each character in a text field can have its own character formatting settings, such as font name, font size, bold, and italic.

For paragraphs, the first character of the paragraph is examined for the paragraph formatting settings for the entire paragraph. Examples of paragraph formatting settings are left margin, right margin, and indentation.

Any text inserted manually by the user, or replaced by the replaceSelectedText() method, receives the default text field formatting for new text, and not the formatting specified for the text insertion point. To set the default formatting for new text, use defaultTextFormat.

Parameters

format:flash.text:TextFormat — A TextFormat object that contains character and paragraph formatting information.
 
beginIndex:int (default = -1) — Optional; an integer that specifies the zero-based index position specifying the first character of the desired range of text.
 
endIndex:int (default = -1) — Optional; an integer that specifies the first character after the desired text span. As designed, if you specify beginIndex and endIndex values, the text from beginIndex to endIndex-1 is updated.

UsageDescription
my_textField.setTextFormat(textFormat:TextFormat)Applies the properties of textFormat to all text in the text field.
my_textField.setTextFormat(textFormat:TextFormat, beginIndex:int)Applies the properties of textFormat to the text starting with the beginIndex position.
my_textField.setTextFormat(textFormat:TextFormat, beginIndex:int, endIndex:int)Applies the properties of the textFormat parameter to the span of text from the beginIndex position to the endIndex-1 position.

Notice that any text inserted manually by the user, or replaced by the replaceSelectedText() method, receives the default text field formatting for new text, and not the formatting specified for the text insertion point. To set a text field's default formatting for new text, use the defaultTextFormat property.


Throws
Error — This method cannot be used on a text field with a style sheet.
 
RangeError — The beginIndex or endIndex specified is out of range.

See also


Example  ( How to use this example )

In the following example, when the text is clicked, a defined range of text, "TEXT IN ALL CAPS," switches format between the default text format and the new format.

An event listener for the myTextField text field is added to respond to the mouse clicks by invoking the clickHandler() method. In the clickHandler() method, the getTextFormat() method returns the current format of a character (index 55) from the intended range of the text, which is then placed in the currentTextFormat TextFormat object. The if statement checks the currentTextFormat text format to see if the character in the range is using the new format (font point is set to 18). If not, the new format changes the size to 18 point, color to red, and applies underline and italics to the range of text between 54-70 (TEXT IN ALL CAPS). If the character in the range is using the new format, the format of the range is set back to the default (original) format of the text field.

package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFormat;  
    import flash.text.TextFieldAutoSize;  
    import flash.events.MouseEvent;

    public class TextField_setTextFormatExample extends Sprite {
        private var myTextField:TextField = new TextField();
        private var newFormat:TextFormat = new TextFormat();
        
        public function TextField_setTextFormatExample() {
            myTextField.autoSize = TextFieldAutoSize.LEFT;
            myTextField.selectable = false;
            myTextField.background = true;
            myTextField.text = "No matter where you click on this text field only the TEXT IN ALL CAPS changes format.";

            myTextField.addEventListener(MouseEvent.CLICK, clickHandler);

            newFormat.color = 0xFF0000;
            newFormat.size = 18;
            newFormat.underline = true;
            newFormat.italic = true;
                
            this.addChild(myTextField);
        }

        private function clickHandler(event:MouseEvent):void {
            var currentTextFormat:TextFormat = myTextField.getTextFormat(55);
            
            if(currentTextFormat.size != 18) {
                myTextField.setTextFormat(newFormat, 54, 70);
            }
            else {
                myTextField.setTextFormat(myTextField.defaultTextFormat);
            }    
        }    
    }
}
Event Detail

change

Event
Event Object Type: flash.events.Event
property Event.type = flash.events.Event.CHANGE

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Dispatched after a control value is modified, unlike the textInput event, which is dispatched before the value is modified. Unlike the W3C DOM Event Model version of the change event, which dispatches the event only after the control loses focus, the ActionScript 3.0 version of the change event is dispatched any time the control changes. For example, if a user types text into a text field, a change event is dispatched after every keystroke.

The Event.CHANGE constant defines the value of the type property of a change event object.

This event has the following properties:

PropertyValue
bubblestrue
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe object that has had its value modified. The target is not always the object in the display list that registered the event listener. Use the currentTarget property to access the object in the display list that is currently processing the event.

Example  ( How to use this example )

In the following example, the text that the user enters (user input) is immediately copied (echoed) into another text field with a different text format.

Two text fields are created, one for the user input and the other (headingTextField) for the copy of the user input. A TextFormat object is also created and the default text format is assigned to the headingTextField text field. When the content of the text field is changed, the changeHandler() method is invoked, which assigns the text in the inputTextField text field to the headingTextField text field. (If the method was called for the TextEvent.TEXT_INPUT event instead of the Event.CHANGE event, the content of the user input is copied only after the user has entered more text.)

package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFieldType;
    import flash.text.TextFormat;
    import flash.text.TextFormatAlign;
    import flash.events.Event;
    
    import flash.events.TextEvent;

    public class TextField_Event_changeExample extends Sprite {
        private var inputTextField:TextField = new TextField(); 
        private var headingTextField:TextField = new TextField(); 
        private var newFormat:TextFormat = new TextFormat();
         
        public function TextField_Event_changeExample() {
            headingTextField.x = 10;
            headingTextField.y = 10;
            headingTextField.height = 30;
            headingTextField.width = 400;
            headingTextField.background = true;
            headingTextField.backgroundColor = 0xF5F5DC;
            headingTextField.selectable = false;
 
            inputTextField.x = 10;
            inputTextField.y = 70;
            inputTextField.height = 20;
            inputTextField.width = 230;
            inputTextField.background = true;
            inputTextField.border = true;
            inputTextField.maxChars = 40;
            inputTextField.wordWrap = true;
            inputTextField.type = TextFieldType.INPUT;

            inputTextField.addEventListener(Event.CHANGE, changeHandler);

            newFormat.bold = true;
            newFormat.size = 18;
            newFormat.color = 0xFF0000;
            newFormat.align = TextFormatAlign.CENTER;

            headingTextField.defaultTextFormat = newFormat;

            this.addChild(inputTextField);
            this.addChild(headingTextField);
        }

        private function changeHandler(e:Event):void {
            headingTextField.text = inputTextField.text;
        }
    }
}

link

Event  
Event Object Type: flash.events.TextEvent
property TextEvent.type = flash.events.TextEvent.LINK

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Dispatched when a user clicks a hyperlink in an HTML-enabled text field, where the URL begins with "event:". The remainder of the URL after "event:" is placed in the text property of the LINK event.

Note: The default behavior, adding the text to the text field, occurs only when Flash Player generates the event, which in this case happens when a user attempts to input text. You cannot put text into a text field by sending it textInput events.

Defines the value of the type property of a link event object.

This event has the following properties:

PropertyValue
bubblestrue
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe text field containing the hyperlink that has been clicked. The target is not always the object in the display list that registered the event listener. Use the currentTarget property to access the object in the display list that is currently processing the event.
textThe remainder of the URL after "event:"

Example  ( How to use this example )

In the following example, the playMP3() function is defined. A TextField object named list is created and populated with HTML text. The text "Track 1" and "Track 2" are links inside the text field. The playMP3() function is called when the user clicks either link. The name of the MP3 file, which follows the string "event:" in the href attribute of the HTML tag, is passed to the linkHandler() method as the text property of the link event object.

package {
    import flash.display.Sprite;
    import flash.errors.IOError;
    import flash.events.IOErrorEvent;
    import flash.events.TextEvent;
    import flash.media.Sound;
    import flash.media.SoundChannel;
    import flash.net.URLRequest;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;

    public class TextField_event_link extends Sprite
    {
        private var myMP3:Sound;
        public function TextField_event_link() {
            myMP3 = new Sound();
            var list:TextField = new TextField();
            list.autoSize = TextFieldAutoSize.LEFT;
            list.multiline = true;
            list.htmlText = "<a href=\"event:track1.mp3\">Track 1</a><br>";
            list.htmlText += "<a href=\"event:track2.mp3\">Track 2</a><br>";
            addEventListener(TextEvent.LINK, linkHandler);
            addChild(list);
        }
        
        private function playMP3(mp3:String):void {
            try {    
                myMP3.load(new URLRequest(mp3));
                myMP3.play();
            }
            catch(err:Error) {
                trace(err.message);
            }
            myMP3.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
        }
        
        private function linkHandler(linkEvent:TextEvent):void {
            playMP3(linkEvent.text);
        }
        
        private function errorHandler(errorEvent:IOErrorEvent):void {
            trace(errorEvent.text);
        }
    }
}

scroll

Event  
Event Object Type: flash.events.Event
property Event.type = flash.events.Event.SCROLL

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Dispatched by a TextField object after the user scrolls.

The Event.SCROLL constant defines the value of the type property of a scroll event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe TextField object that has been scrolled. The target property is not always the object in the display list that registered the event listener. Use the currentTarget property to access the object in the display list that is currently processing the event.

Example  ( How to use this example )

The following example defines two TextField objects. The first TextField object has two associated event handlers. When you click the mouse inside this first text field, the mouseDown event is dispatched, and the associated mouseDownScroll handler is called. The mouseDownScroll() handler causes the field to scroll. Then, the scroll event is dispatched, and the associated scrollHandler() handler updates the second text field to display the current scroll position.

package
{
    import flash.display.Sprite;
    import flash.text.*;
    import flash.events.Event;
    import flash.events.TextEvent;
    import flash.events.MouseEvent;

    public class TextScrollExample extends Sprite
    {
        private var myTextBox1:TextField = new TextField();
        private var myTextBox2:TextField = new TextField();
        private var myText:String = "Hello world and welcome to the show. It's really nice to meet you. Take your coat off and stay a while. OK, show is over. Hope you had fun. You can go home now. Don't forget to tip your waiter. There are mints in the bowl by the door. Thank you. Please come again.";

        public function TextScrollExample()
        {
            myTextBox1.text = myText;
            myTextBox1.width = 200;
            myTextBox1.height = 50;
            myTextBox1.multiline = true;
            myTextBox1.wordWrap = true;
            myTextBox1.background = true;
            myTextBox1.border = true;
            
            myTextBox2.x=220;
            myTextBox2.text="scrolled to line: " + myTextBox1.scrollV;

            addChild(myTextBox1);
            addChild(myTextBox2);
            myTextBox1.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownScroll);
            myTextBox1.addEventListener(Event.SCROLL, scrollHandler);
        }

        public function mouseDownScroll(event:MouseEvent):void
        {
            myTextBox1.scrollV++;
        }
        public function scrollHandler(event:Event):void
        {
           myTextBox2.text="scrolled to line: " + myTextBox1.scrollV;
        }
    }
}

textInput

Event  
Event Object Type: flash.events.TextEvent
property TextEvent.type = flash.events.TextEvent.TEXT_INPUT

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9, Flash Lite 4

Flash Player dispatches the textInput event when a user enters one or more characters of text. Various text input methods can generate this event, including standard keyboards, input method editors (IMEs), voice or speech recognition systems, and even the act of pasting plain text with no formatting or style information.

Defines the value of the type property of a textInput event object.

Note: This event is not dispatched for the Delete or Backspace keys.

This event has the following properties:

PropertyValue
bubblestrue
cancelabletrue; call the preventDefault() method to cancel default behavior.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe text field into which characters are being entered. The target is not always the object in the display list that registered the event listener. Use the currentTarget property to access the object in the display list that is currently processing the event.
textThe character or sequence of characters entered by the user.

Example  ( How to use this example )

The following example defines two TextField objects: the first TextField object is an input text field, and the second TextField object is a dynamic text field. As you enter text characters in the first text field, the textInput event is dispatched, the textInputHandler() handler is called, and the characters display in the second text field. When you paste a block of text into the input field, the event handler copies the entire block into the other field.

package
{
    import flash.display.Sprite;
    import flash.text.*;
    import flash.events.Event;
    import flash.events.TextEvent;
    import flash.events.MouseEvent;

    public class TextInputExample extends Sprite
    {
        private var myTextBox1:TextField = new TextField();
        private var myTextBox2:TextField = new TextField();

        public function TextInputExample()
        {
            myTextBox1.type = TextFieldType.INPUT;
            myTextBox1.width = 200;
            myTextBox1.height = 20;
            myTextBox1.background = true;
            myTextBox1.border = true;
            
            myTextBox2.x=220;

            addChild(myTextBox1);
            addChild(myTextBox2);
            myTextBox1.addEventListener(TextEvent.TEXT_INPUT,textInputHandler);
        }

        public function textInputHandler(event:TextEvent):void
        {
           myTextBox2.text=event.text;
        }
    }
}
TextFieldExample.as

The following example uses the TextFieldExample class to display a text message. This is accomplished by using the following steps:
  1. A label property of type TextField is created.
  2. The class constructor calls the configureLabel() function.
  3. The configureLabel() method first creates a new TextField object and assigns it to the label property, and then sets its parameters to the following:
    • Left-justify the text field.
    • Enable the background fill.
    • Enable the border.
  4. The configureLabel() method creates the format variable and assigns it to a new TextFormat instance with its parameters set to the following:
    • Font type = Verdana
    • Font color = solid red
    • Font size = 10
    • Font underline = true
  5. The defaultTextFormat property of the label text field is set to format, and the label instance is added to the display list, which initially displays a text field with no text on the stage.
  6. The constructor sets the text of the label text field to "Hello world and welcome to the show." by calling the setLabel() method.
package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.text.TextFormat;


    public class TextFieldExample extends Sprite {
        private var label:TextField;
        private var labelText:String = "Hello world and welcome to the show.";

        public function TextFieldExample() {
            configureLabel();
            setLabel(labelText);
        }

        public function setLabel(str:String):void {
            label.text = str;
        }

        private function configureLabel():void {
            label = new TextField();
            label.autoSize = TextFieldAutoSize.LEFT;
            label.background = true;
            label.border = true;

            var format:TextFormat = new TextFormat();
            format.font = "Verdana";
            format.color = 0xFF0000;
            format.size = 10;
            format.underline = true;

            label.defaultTextFormat = format;
            addChild(label);
        }
    }
}