[Change the scale, background color, or frame rate of the output swf]
In the "Navigator" window, right-click your project, select "Properties", select "ActionScript Compiler", and enter the required command in "Additional compiler arguments ".
To change the background color, enter-default-background-color 0 xffffff.
[Mouse coordinates]
MouseX mouseY
[Check the variable type and return a Boolean value]
Is
[Check the variable type and return the type]
Typeof
[Check the object type and return this object]
As
[It's a number, but it's not a valid number]
Var quantity: Number = 15-"rabbits ";
Trace (typeof quantity); // display: "number", but it is NaN (not a number)
Trace (quantity is Number); // true
Trace (quantity! = NaN); // false
// Use the isNaN () function to detect:
IsNaN (quantity); // true
// Check whether the variable contains valid numbers:
! IsNaN (quantity); // false
Cancel the strict compiling mode by default]
In the "Navigator" window, right-click your project, select "Properties", and select "ActionScript Compiler"> cancel "Enabel compile-time type checking ".
The basic metadata type and complex data type are like "value type" and "reference type "]
The basic metadata type is similar to passing by value:
Var intOne: int = 1;
Var intTwo: int = 1;
Trace (intOne = intTwo); // true
[Transfer complex data types by reference]
Var arrayOne: Array = new Array ("a", "B ");
Var arrayTwo: Array = arrayOne;
Trace (arrayOne = arrayTwo); // true
//-----------------------------------
Var arrayOne: Array = new Array ("a", "B ");
Var arrayTwo: Array = new Array ("a", "B ");
Trace (arrayOne = arrayTwo); // false
[Optimize the logic AND (&) and or (|) knowledge]
For logic And (&&):
Unless the First Half of the conditional expression is true, the latter half of the logical AND operator is not calculated in the event of an event. if the first half is false, the entire condition expression must be false. Therefore, it is inefficient to calculate the second half.
For logic OR (| ):
Unless the First Half of the conditional expression is false, the latter half of the logical OR operator is not evaluated in the event of event action. If the first half is true, the entire conditional expression must be true.
Conclusion: When logical AND (&) is used, put the expression that is most likely to be false in front of the result. When logical OR (|) is used, put the expression most likely to be true in front.
[Timer considerations]
Do not think that Timer can be extremely accurate; Use Timer time interval should not be less than 10 milliseconds.
[Private, protected, internal, public access permission]
Private: It can only be accessed within the class itself. By convention, the name of a private member starts with an underscore;
Protected: can be accessed by the class itself or any subclass. however, this is based on instances. in other words, a class instance can access its own protected members or the protected members of its parent class, but cannot access the protected members of other instances of the same class, when naming a protected member, the following line starts;
Internal: can be accessed by the class itself or any class in the same package;
Public: it can be accessed inside the class, or by a class instance, or declared as static, it can be accessed directly from the class.
[A function has an unknown number of parameters, and uses the arguments object or the "... (rest)" symbol to access its parameters]
Note: using the "... (rest)" parameter will make the arguments object unavailable;
Private funciton average (): void {
Trace (arguments. length); // number of output parameters
// The arguments type is object, but it can be accessed just like an array.
Trace (arguments [1]); // output the second parameter
}
Private function average (... argu): void {
Trace (argu [1]); // output the second parameter. The argu parameter name is customized.
}
[Try, catch, finally]
Private function tryError (): void {
Try {
Trace ("Test start-try ");
ThrowError ();
} Catch (errObject: Error ){
Trace ("error message:" + errObject. message );
Trace ("test end-catch ");
Return;
} Finally {
Trace ("Although the return method already exists in catch, the code in finally after the return method will still be executed. in fact, no matter whether the return method is in try or catch, the code in finally will always be executed ");
}
Trace ("there is already a return, and this will not be executed again. Unless no error is thrown, so that the code in the catch is not executed ");
}
Private function throwError (): void {
Throw new Error ("throw Error ");
}
[For... in and for each... in]
And... the difference in loop is that for each... the iteration variable in the in loop contains the value saved by the attribute, but does not contain the attribute name (or primary key, index ).
Tips for naming a package path]
It is better to use the package name corresponding to the owner and related projects. by convention, the package name should start with the reverse URL name. for Example, if Example Corp (examplecorp.com) writes some ActionScript3.0 classes, all classes will be placed in com. in the examplecorp package (or com. in the subpackage of examplecorp ). in this way, if there is another Example Corp (examplecorp. co. uk) also writes some ActionScript3.0 classes, as long as you use the uk package. co. examplecorp to ensure uniqueness.
When a class is part of a specific application, it should be placed in a specific sub-package of the application. for Example, Example Corp may have an application named WidgetStore. if the WidgetStore application uses a class named ApplicationManager, the class should be placed in com. examplecorp. in the widgetstore package, or in the sub-package of the package.
Traditionally, the package name starts with a lowercase letter.
[Implicit getter and setter )]
Public function get count (): uint {
Return _ count;
}
Public function set count (value: uint): uint {
If (value <100 ){
_ Count = value;
} Else {
Throw Error ();
}
}
[Make sure that the class will never have child classes. Use final]
Final public class Example {}
[Use of super keywords]
Super (); // constructor of the parent class, which can only be used within the class instance Constructor
Super. propertyName; // call the attributes of the parent class. The attribute must be declared as public or protected.
Super. methodName (); // call the method of the parent class. The method must be declared as public or protected.
[Create a constant and use the keyword const instead of var]
Static public const EXAMPLE: String = "example ";
[Detect the Player version]
Flash. system. Capabilities. version
This method is not applicable to any Flash Player versions earlier than Version 8.5.
[Judge the client system]
Flash. system. Capabilities. OS
[Detection player type]
Flash. system. Capabilities. playerType
Possible values include:
StandAlone for independent Flash Player
"External", used for External Flash Player or in testing mode
"PlugIn" for Flash Player browser plug-ins
"ActiveX", used for the Flash Player ActiveX Control used by Microsoft Internet Explorer
Detection System Language]
Flash. system. Capabilities. language
[Determine whether the IME (Input Method Editor) is enabled )]
Flash. system. IME. enabled
[Screen Resolution Detection]
Flash. system. Capabilities. screenResolutionX
Flash. system. Capabilities. screenResolutionY
[Center the pop-up window with the algorithm]
X = (stage width/2)-(window width/2)
Y = (stage height/2)-(window height/2)
[Control the video matching Player mode, including scaling problems]
Stage. scaleMode
Available value: flash. display. StageScaleMode
[Stage alignment mode]
Stage. align
Available value: flash. display. StageAlign
[Hide the right-click menu of Flash Player]
Stage. showdefaconcontextmenu = false;
[Check whether the system has the audio function]
Flash. system. Capabilities. hasAudio
[Check whether the player runs on a system with an MP3 decoder or a system without an MP3 decoder]
Flash. system. Capabilities. hasMP3
Check whether the player can play streaming videos (true) or not (false]
Flash. system. Capabilities. hasStreamingVideo
[Check whether the player runs on a system that supports (true) Video embedding or a system that does not support (false) Video embedding]
Flash. system. Capabilities. hasEmbeddedVideo
Check whether the player can (true) or not (false) encode the video stream (such as the video stream from the Web camera]
Flash. system. Capabilities. hasVideoEncoder
[Display the "Security Settings" Panel in Flash Player]
Flash. system. Security. showSettings ();
Optional items: flash. system. SecurityPanel
To allow .swf's local .swf]
Add flash. system. Security. allowDomain () to the .swf file of the local domain ()
Or use the security policy file "crossdomain. xml ". before Flash 8, the file is stored in the root directory of the .swf domain. Now you can use flash. system. security. loadPolicyFile () indicates the location of the security policy file. deny any domain by entering nothing in the <cross-domain-policy> label. The security policy file also supports the common character "*":
<? Xml version = "1.0"?>
<! -- Http://www.mydomain.com/crossdomain.xml -->
<Cross-domain-policy>
<Allow-access-from domain = "www.riahome.cn"/>
<Allow-access-from domain = "* .Y-boy.cn"/>
<Allow-access-from domain = "210.38.196.48"/>
<Allow-access-from domain = "*"/>
</Cross-domain-policy>
[Conversion between numbers in different hexadecimal notation]
ParseInt (str: String, radix: uint = 0): Number returns the decimal Number. The radix parameter indicates the base Number of The Number to be analyzed. if radix is omitted, the default value is 10, unless the string starts with "0x", "0X" or "0 ":
Trace (parseInt ("0x12"); // set radix to 16 and output to 18.
Trace (parseInt ("017"); // set radix to 8, output: 15
Or use the toString (radix) method of the Number, uint, and int objects.
[Use Math. round () to round a number]
Math. round ()
Trace (Math. round (204.499); // output: 204
Trace (Math. round (401.5); // output: 402
[Use Math. floor () to round down a number, that is, as long as the integer part does not care about the decimal part]
Trace (Math. floor (204.99); // output: 204
[Use Math. ceil () to round up a number. If the fractional part is not zero, add 1 to the integer part]
Trace (Math. ceil (401.01); // output: 402
[Generate a random number]
Use Math. random () to generate a pseudo-random number n, where 0 <= n <1
[Take the number to the nearest decimal point, that is, specify the accuracy]
1. determine the number of decimal places for the number you want to take. For example, if you want to get 90.337 to 90.34, it means you want to get two decimal places, that is, you want to get the nearest 0.01;
2. Divide the input value by the number selected in step 1 (0.01 in this example );
3. Use Math. round () to calculate the value calculated in step 2 as the nearest integer;
4. Multiply the result obtained from step 3 by the value used for Division in step 2.
For example, to set 90.337 to two decimal places, you can use:
Trace (Math. round (90.337/0.01) * 0.01); // output: 90.34
[Take the number as the nearest multiple of an integer]
In example 1, 92.5 is taken as the nearest factor of 5:
Trace (Math. round (92.5/5) * 5); // output: 95
For example 2, 92.5 is taken as the nearest factor of 10:
Trace (Math. round (92.5/10) * 10); // output: 90
[Obtain a random number within the specified value range]
// Optional values: [min, max]
Private function randRange (min: Number, max: Number): Number {
Var randomNum: Number = Math. floor (Math. random () * (max-min + 1) + min;
Return randomNum;
}
Example:
Simulate silver coins, that is, to obtain a random Boolean value (true or false): randRange (0, 1 );
Simulate the dice, that is, you want to get the random six values: randRange (1, 6 );
To avoid being cached, a unique number needs to be appended to the end of the URL. The best way is to obtain the current number of milliseconds.
[Radian and degree conversion]
Convert from radian to degree: degrees = radians * 180/Math. PI
Converts degrees to radians: radians = degrees * Math. PI/180
Calculate the distance between two points]
Stock theorem: c2 = a2 + b2
Assume that there are two video clips, mc1 and mc2, and the distance between them is c:
Var c: Number = Math. sqrt (Math. pow (mc1.x-mc2.x, 2) + Math. pow (mc1.y-mc2.y, 2 ));
Simulate circular motion]
Obtain the coordinates of any point P (x, y) on the circle with the known center o (x0, y0), radius r, and radian angle:
X = x0 + (Math. cos (angle) * r );
Y = y0 + (Math. sin (angle) * r );
Note: The X axis of the stage is horizontal to the right, and the Y axis is vertical to the down.
Simulate elliptical motion]
We know the coordinates of any point P (x, y) on the circle, such as o (x0, y0), long axis a, short axis B, and radian angle:
X = x0 + (Math. cos (angle) * );
Y = y0 + (Math. sin (angle) * B );
[Conversion between Fahrenheit and Celsius temperature]
Fahrenheit temperature = degrees Celsius x 9/5 + 32
Temperature in Celsius = (Fahrenheit-32) * 5/9
[Conversion between kilograms and LBS]
KG = LB * 2.2
LBs = kg/2.2
[Add elements to the end of the array]
Var array: Array = new Array ();
Array. push ("a", "B ");
// You can add a single element to the end of the array as follows:
Array [array. length] = "c ";
// If the element set with the index does not exist, the array itself will automatically expand to include enough elements. The element between the middle will be set to undefined:
Array [5] = "e ";
Trace (array [4]); // output: undefined
[Add elements to the beginning of the array]
Var array: Array = ["a", "B"];
Array. unshift ("c", "d ");
Trace (array); // output: c, d, a, B
[Delete the first element in the array and return the element. Use the shift () method]
Var letters: Array = new Array ("a", "B", "c ");
Var firstLetter: String = letters. shift ();
Trace (letters); // output: B, c
Trace (firstLetter); // output:
[Delete the last element in the array and return the value of the element. Use the pop () method]
Var letters: Array = new Array ("a", "B", "c ");
Trace (letters); // output: a, B, c
Var letter: String = letters. pop ();
Trace (letters); // output: a, B
Trace (letter); // output: c
[Delete the elements in the array, add new elements to the array, and return the deleted elements. Use the splice () method]
Splice (startIndex: int, deleteCount: uint,... values): Array
StartIndex: an integer that specifies the index of the element at the position where insertion or deletion starts in the array;
DeleteCount: an integer that specifies the number of elements to be deleted;
... Values: an optional list or array of one or more values separated by commas. This list or array is inserted to the position specified by the startIndex parameter in this array.
[Search for the first matched element in the array]
Var array: Array = ["a", "B", "c", "d", "a", "B", "c", "d"];
Var match: String = "B ";
For (var I: int = 0; I <array. length; I ++ ){
If (array [I] = match ){
Trace ("Element with index" + I + "found to match" + match );
// Output: Element with index 1 found to match B
Break;
}
}
[Find the last matched element in the array]
Var array: Array = ["a", "B", "c", "d", "a", "B", "c", "d"];
Var match: String = "B ";
For (var I: int = array. length-1; I> = 0; I --){
If (array [I] = match ){
Trace ("Element with index" + I + "found to match" + match );
// Output: Element with index 5 found to match B
Break;
}
}
Convert a string to an array]
Use the String. split () method:
Var list: String = "I am YoungBoy .";
Var words: Array = list. split (""); // use a space as the separator to cut the string
Trace (words); // output: I, am, YoungBoy.
Convert an array to a string]
Use the String. join () method:
Var myArr: Array = new Array ("one", "two", "three ");
Var myStr: String = myArr. join ("and ");
Trace (myArr); // output: one, two, three
Trace (myStr); // output: one and two and three
[Use an object array to process related data]
Var cars: Array = new Array ();
Cars. push ({make: "Mike", year: 1997, color: "blue "});
Cars. push ({make: "Kelly", year: 1986, color: "red "});
For (var I: int = 0; I <cars. length; I ++ ){
Trace (cars [I]. make + "-" + cars [I]. year + "-" + cars [I]. color );
}
// Output:
// Mike-1997-blue
// Kelly-1986-red
Obtain the minimum or maximum value in the array]
Var scores: Array = [10, 4, 15, 8];
Scores. sort (Array. NUMERIC );
Trace ("Minimum:" + scores [0]);
Trace ("Maximum:" + scores [scores. length-1]);
[Use the for... in statement to read the associated array elements]
Var myObject: Object = new Object ();
MyObject. name = "YoungBoy ";
MyObject. age = 20;
For (var I: String in myObject ){
Trace (I + ":" + myObject [I]);
}
// Output: name: YoungBoy
// Age: 20
Note:... the in loop does not display all the built-in attributes of the object. for example, a loop shows the new special attributes during execution, but does not list the built-in object methods, even if they are stored in the object attributes.
[AVM (ActionScript Virtual Machine, Virtual Machine) and Rendering Engine (Rendering Engine )]
AVM is responsible for executing the ActionScript program, while the rendering engine draws the object on the display.
[Number of display objects in the container display list]
Each container has the numChildren attribute.
[Add a project to the display list]
AddChild (child: DisplayObject)
AddChildAt (child: DisplayObject, index: int)
Index: The index location of the subitem. If you specify the index location currently occupied, this location and all the sub-objects at a higher position will be moved to the sublevel list.
Remove a project from the display list]
RemoveChild (child: DisplayObject)
RemoveChildAt (index: int)
Index: the sub-index of the DisplayObject To be deleted. The index position of any displayed object on this sub-item is equal to 1.
To remove all child elements from the window, you can combine removeChildAt (), numChildren attributes, and for loop. because the index position changes every time a sub-component is removed, there are two ways to remove all sub-components:
1. always remove sub-components whose position is 0;
2. Remove the sub-component from the tail end.
[Change the position of an existing sub-item in the display object container]
SetChildIndex (child: DisplayObject, index: int): void
Possible methods:
Returns the index location of the child instance of DisplayObject: getChildIndex (child: DisplayObject): int.
Returns the instance of the sub-Display object at the specified index: getChildAt (index: int): DisplayObject.
Note: When the sub-component moves to an index lower than its current location, all sub-components of the index before the sub-component index will increase the index by 1 from the base index, the sub-component is specified as the index of the target. when a sub-component moves to a higher index, it starts from the index on the sub-component index until all sub-components of the index will make the index drop by 1, the sub-component is specified to the index value of the target.
[Tips for vertical text placement in TextField at the center of the button surface]
TextField. y = (_ height-textField. textHeight)/2;
TextField. y-= 2; // subtract 2 pixels to adjust the offset
External Department .swf video loading and Interaction]
1. Listen to the init event;
2. Access the loaded video through the content attribute.
When the loaded video has enough initialization work to make its method and attributes interactive, the init event will be initiated. the video can be controlled only after the loader initiates the init event. the loaded video tries to interact with it before initialization, which may cause errors during execution.
_ Loader. contentLoaderInfo. addEventListener (Event. INIT, handleInit); // when the attributes and methods of .swf are available
_ Loader. load (new URLRequest ("ExternalMovie.swf "));
Private function handleInit (event: Event): void {
Var movie: * = _ loader. content;
Trace (movie. getColor ());
Movie. setColor (0xFF0000 );
}
TextField has two types: dynamic (dynamic) and input (input). The default value is dynamic. Change the TextField type method]
Field. type = TextFieldType. INPUT; // The default value of the selectable attribute is true.
Flash. text. TextFieldType. INPUT and flash. text. TextFieldType. DYNAMIC
[Filter text input]
TextField. restrict = "this is input content ";
Field. restrict = "^ The input content is not allowed here ";
The restrict attribute supports regular expressions:
Field. restrict = "a-zA-z"; // only letters in size are allowed
Field. restrict = "a-zA-z"; // only letters and spaces are allowed
Field. restrict = "0-9"; // only numbers are allowed
Field. restrict = "^ abcdefg"; // no other than the lowercase letter abcdefg
Field. restrict = "^ a-z"; // all lowercase letters are not allowed. However, other contents are allowed, including uppercase letters.
Field. restrict = "0-9 ^ 5"; // only numbers are allowed, except for 5
Make the restrict character contain special letters (such as-and ^ ):
Field. restrict = "0-9 \-"; // allows numbers and break numbers
Field. restrict = "0-9 \ ^"; // allow numbers and ^
Field. restrict = "0-9 \\\\"; // allow numbers and backslash
You can also use the Unicode escape sequence to specify the allowed content. For example:
Field. restrict = "^ \ u001A ";
Note: ActionScript is case-sensitive. If the restrict attribute is set to abc, uppercase letters (A, B, and C) are allowed, B and c), and vice versa. the restrict attribute only affects the content that users can enter. The script can put any text into text fields.
[Set the maximum length of the input box]
TextField. maxChars: int
[Append content to TextField]
TextField. appendText (text: String): void
This method is more efficient than concatenating two strings (for example, field. text + = moreText) by adding values to the text attribute.
Show HTML text]
TextField.html Text = "<B> Html text </B> ";
Supported HTML Tag sets include: <B>, <I>, <u>, <font> (with face, size, and color attributes), <p>, <br>, <a>, <li>, , and <textformat> (attributes include leftmargin, rightmargin, blockindent, indent, leading, and tabstops, corresponding to attributes of the same name in the TextFormat class)
[Blank reduction]
TextField. condenseWhite = true;
Delete extra spaces (spaces, line breaks, etc.) in text fields with HTML text, as most HTML browsers do.
Note: Set the condenseWhite Attribute before setting the htmlText attribute.
[Automatic size adjustment and alignment]
TextField. autoSize = TextFieldAutoSize. LEFT;
Optional values:
Flash. text. TextFieldAutoSize. CENTER
Flash. text. TextFieldAutoSize. LEFT
Flash. text. TextFieldAutoSize. NONE
Flash. text. TextFieldAutoSize. RIGHT
Indicates whether a text field is automatically wrapped]
TextField. wordWrap = true; // wrap automatically
[Use a program to scroll the text]
The horizontal direction is measured in pixels, while the vertical direction is measured in rows:
ScrollV: Specifies the top line of the visible area of the text box, which can be read and written;
BottomScrollV: Specifies the bottom visible lines in the text box, read-only;
MaxScrollV: the maximum value of scrollV, read-only;
NumLines: defines the number of lines of text in multi-line text fields, read-only;
TextField. scrollV = field. maxScrollV; // scroll to the last page
[Response to rolling events]
Field. addEventListener (Event. SCROLL, onTextScroll );
[Style text method]
1. Use HTML tags for styling;
2. Use TextFormat object;
3. Use CSS.
For example, HTML uses the <font> label, TextFormat object sets the font attribute, and CSS uses the font-family attribute.
Supported Cascading Style Sheet (CSS) attributes and values, and corresponding names of The ActionScript attributes (in parentheses ):
Color (color), display (display), font-family (fontFamily), font-size (fontSize), font-style (fontStyle), font-weight (fontWeight ), kerning (kerning), leading (leading), letter-spacing (letterSpacing), margin-left (marginLeft), margin-right (marginRight), text-align (textAlign ), text-decoration (textDecoration), text-indent (textIndent)
Supported HTML entities: <(less than: <),> (greater than:>), & (and: &), "(double quotation marks:"), '(Marker, single quotes :')
Two styles are written:
Statement 1:
Var sampleStyle: Object = new Object ();
SampleStyle. color = "# FFFFFF ";
SampleStyle. textAlign = "center ";
Css. setStyle (". sample", sampleStyle );
Statement 2:
Var sampleStyle: Object = {color: "# FFFFFF", textAlign: "center "};
Css. setStyle (". sample", sampleStyle );
[Style the text entered by the user]
When the defaultTextFormat attribute is used, the style is applied to the text in the input box:
Var formatter: TextFormat = new TextFormat ();
Formatter. color = 0x0000FF; // convert the text to blue
Field. defaultTextFormat = formatter;
[Style part of existing text]
TextFormat. setTextFormat (format: TextFormat, beginIndex: int =-1, endIndex: int =-1): void
[Set text box font]
Example:
HTML: field.html Text = "<font face = 'arial'> Formatted text </font> ";
TextFormat: formatter. font = "Arial ";
CSS: P {font-family: Arial ;}
You can also use a comma-separated font list: formatter. font = "Arial, Verdana, Helvetica ";
Note:
The font and font groups are different. There are three types of font groups: _ sans, _ serif, and _ typewriter.
_ Sans groups generally refer to fonts such as Arial or Helvetica;
_ Serif groups generally refer to fonts such as Times or Times New Roman;
The _ typewriter group generally refers to the font of Courier or Courier New.
[Embedded font]
Use [Embed] And then set the tag. the [Embed] label should appear in the ActionScript file and be out of class declaration. you can embed TrueType fonts or system fonts. syntax for embedding TrueType fonts:
[Embed (source = "pathToTtfFile", fontName = "FontName", mimeType = "application/x-font-truetype")]
PathToTtfFile: Path of the ttf file. The path of the TrueType font can be relative or absolute;
FontName: font name;
Syntax for embedded system fonts:
[Embed (systemFont = "Times New Roman", fontName = "Times New Roman", mimeType = "application/x-font-truetype")]
FontName: use the same name as the actual system font name.
Note: When using embedded fonts, set the embedFonts attribute of TextField to true, so that TextField can only use embedded fonts. if you try to use the device font for TextField with embedFonts set to true, nothing will be displayed. if embedFonts is set to true, you cannot specify the word list separated by commas.
[Create a text that can be rotated]
Use the embedded font. When you rotate the text box, the font of the device disappears.
[Display Unicode text]
1. Load Unicode text from external sources;
2. If your editor supports Unicode (such as Flex Builder), you can use this character directly in the ActionScript program;
3. Use Unicode escape characters. All Unicode escape characters in ActionScript start with \ u, followed by four hexadecimal numbers.
Note: If you want to obtain Unicode characters, use: Start> All Programs> accessories> System Tools> character ing table in Windows.
[Bring the focus of Flash Player to the text box]
Stage. focus = field;
Remove focus:
Stage. focus = null;
Note: When the .swf file is first loaded to a Web browser, there is no focus. therefore, before you specify the focus to an element of the Flash application in the form of a program, you must first move the focus to Flash Player.
[Select text using ActionScript]
Use TextField. setSelection (beginIndex: int, endIndex: int): void
To properly select text, the text box must have the focus:
Stage. focus = field; // set the focus to the text box.
Field. text = "This is example text"; // set text
Field. setSelection (0, 4); // highlight the word "This ".
Use the read-only selectionBeginIndex and selectionEndIndex attributes to access the index of the selected character range.
[Set the insert point (cursor position) in the text and access the index value of the cursor position]
You can use TextField. setSelection () to set the index parameters at the beginning and end to the same value, and set the cursor position in the text (assuming the focus ):
Field. setSelection (0, 0); // place the insertion point before the first character
Trace (field. caretIndex); // output the index value of the cursor position