Flash supports three types of text fields: static, dynamic, and input. Static text fields can only be created visually on the Stage using the Text tool, located in the toolbox on the right side of the screen, and contain text that will not change as the movie runs. Headings, labels on navigation buttons, descriptive text, and footer information such as copyright notices are usually placed in static text fields.
Text that will need to change at runtime is placed in dynamic text fields. These fields can be created visually on the Stage using the same Text tool that you use to create a static field, or they can be created through code in ActionScript. Text can be placed in them initially when you draw the field on the Stage, and that text can then be changed as the movie plays via ActionScript.
Alternatively, the field can be left empty initially and populated later through code. You can use dynamic text fields to store player scores in games and quizzes, the name of the user currently viewing the movie, the name of a video or picture that is being displayed, or just about anything else.
When you create a dynamic text field on the Stage, you need to provide an instance name for the field, just as you would for a MovieClip
or Button
instance. As a convention, text
fields are usually named beginning with a txt prefix, followed by a descriptive name for the purpose of the field, so a field used to store a player name could be txtPlayerName
.
Dynamic and input text fields are instances of the TextField
class. Input text fields are discussed in detail later in this chapter.
The Save As dialog box appears.
The file is saved with the dynamic text field on the Stage.
When setting the type of field in the Properties panel, be aware that Flash will remember what you used last time. If you create a field and set the type to dynamic text, the next field that you draw will automatically be a dynamic field. To create a different type of field, you can change the setting before you draw it or after; either will work. However, be careful when changing the type before you draw the field to make sure that no existing fields are selected when you make the change. If they are, you will be changing their type rather than setting the type for the next field to be drawn. You can ensure that nothing is selected on the Stage by either clicking a blank area of the Stage with the Selection tool or by clicking Edit
Dynamic text fields, like MovieClips
, can be created either visually or in code. Likewise, you can create input text fields using either method, but you can only create static text fields visually on the Stage.
Creating a dynamic text field in code involves first creating a variable to reference the field. The variable name should follow the normal conventions for naming a text field, so it should begin with txt
and be descriptive of the field's purpose. Set the variable to be of type TextField
and use the new keyword to call the TextField
class constructor:
var txtMyName:TextField = new TextField();
You can then add the field to the page by calling the addChild()
method of the Stage, passing to it the name of the field that you defined. You can then set properties on the field, such as the width of the field and its x and y position on the Stage.
You can add text to the field through either its text
or htmlText
property. Simple text can be added by setting the value of the text
property to any string. The use of htmlText
is discussed in Chapter 10. You can apply formatting to the text in the field through the TextFormat
class, which is also discussed in Chapter 10.
See Chapter 1 for details.
The movie plays, displaying the text field.
You can set the width of the field to automatically expand to fit whatever text you might place in it by setting the autoSize
property to one of the three constants defined in the TextFieldAutoSize
class: LEFT, RIGHT
, or CENTER
. Which you choose will also define how the text aligns within the field, so if you want to autosize the field and have the text left-aligned, set
txtPictureName.autoSize = TextFieldAutoSize .LEFT;
If you want the text to wrap within the field, set the wordWrap
and multiline
properties to true:
txtPictureName.multiline = true; txtPictureName.wordWrap = true;
Applying all three values shown here will cause the field to apply any specified width but resize the height to fit the text.
In order to allow your user to enter text into your movie, you need to provide input text fields. Input text fields can also be thought of as form fields and behave in much the same way as text fields in HTML forms.
To create an input field visually on the Stage, you use the Text tool, just as you would to create a static or dynamic field. You can set the field type to Input
in the Properties panel. As with dynamic fields, you will want to provide an instance name, following the same naming conventions as with other text fields.
You can also use the Properties panel to specify the font face, size, and color of the text that the user will see as he or she types. You can choose to show a border around the field, in which case a thin black line will be drawn around the field. If you leave this setting off, the field will be invisible, so you will need to be sure to provide some other visual clue, such as a rectangle drawn on another layer, to let the user know where the field is. The Properties panel includes a Paragraph formatting section that enables you to designate the field as allowing more than one line of text and an Options section to set the maximum number of allowed characters. You will usually use a static text field to provide a label for the field.
The movie plays and shows the field.
The text is entered into the field.
Flash automatically embeds fonts used in static text fields but does not automatically embed fonts specified for input fields. Therefore, if you want to use a nonstandard font — anything other than Arial, Times New Roman, Courier, or Verdana — you need to tell Flash to embed the characters for your font. You can do this from the Properties panel by clicking the Character Embedding button and selecting which characters from the font you want to embed. For dynamic fields, you may need to embed all characters from the font, but input fields generally need only those characters that can be directly typed on the keyboard, such as letters, numbers, and punctuation. This will add to the file size of the final SWF. You can avoid this increase by either using a font that you can be relatively sure all users have, such as Arial or Times New Roman, or even better use one of the device fonts: _serif, _sans, or _typewriter, in which case Flash Player will simply use a font of that type from the user's computer.
Input text fields, like dynamic fields, are instances of the TextField
class. Therefore, they are created in code in precisely the same way as dynamic fields. You begin by providing a name and using the new
keyword to call the class constructor, then use the addChild()
method to add the field to the display list, and finally, set any other properties, such as position and width:
var txtUserName:TextField = new TextField(); addChild(txtUserName);
However, if you simply use the preceding code, you will end up with a dynamic field. The difference between a dynamic and input text field in code is the value of the text field's type property, which will be set to one of two constants from the TextFieldType
class: DYNAMIC
or INPUT:
txtUserName.type = TextFieldType.INPUT;
As with input fields you draw using the visual tools, input fields created in code will by default not display a border, so you will either need to provide a visual outline for the field elsewhere in your movie or set the border
property of the field to true
.
See Chapter 1 for details.
The movie plays, displaying the text field.
The value is entered into the field.
When you create an input text field visually, you can use the Properties panel to set the font, size, and color of the text being entered. It is possible to do the same with code-generated fields, but you cannot simply call a font or fontSize
or similar property of the field. Instead, you must create an instance of the TextFormat
class and then use it to set the properties, which can then be applied to the field. Formatting fields in code with the TextFormat
class is covered in Chapter 10.
Input fields drawn on the Stage most often use static fields for their associated labels. However, you cannot create a static field in ActionScript, so if you want to create a label for an input field, you need to create a dynamic field. You can position the dynamic field next to the input field by providing appropriate x and y coordinates for each.
TextFields
, like other classes in ActionScript, have events associated with them that allow you to perform actions in response to interactions with the field. In addition to standard events such as click, TextFields
have four specialized events: change, link, scroll
, and textInput
. Each of these events are represented by related constants of the TextEvent
class: CHANGE, LINK, SCROLL
, and TEXT_INPUT
.
The change
event is called whenever the contents of the field are changed in any way. If a user is typing in the field, the event is dispatched after every keystroke. You can use this, for example, to copy the user's input in real time into another field. Note that in other languages such as JavaScript, the change
event occurs only when the field loses focus, but in ActionScript, it is triggered with each keystroke.
The link
event is called when a user clicks hyperlinked text within an HTML-formatted text field. HTML-formatted text fields are discussed in Chapter 10.
The scroll
event occurs when a user scrolls through text. The event is actually dispatched after the user finishes scrolling, so it can be used only for actions that should be triggered after the scroll. For example, you may have a text field that displays a license agreement for a download. You could use the scroll
event to activate the button to agree to the terms only when the user scrolls to the bottom, thereby forcing the user to at least scroll through the agreement before continuing.
The textInput
event is dispatched when the user enters text into the field. The text can be entered using a keyboard, speech recognition system, or paste. As with the change
event, this is triggered after each keystroke if the user is typing.
See the sections "Create an Input Text Field Visually" and "Create an Input Text Field in Code" for details.
See the first two sections of this chapter for details.
The movie plays.
Both the change
and textInput
events are dispatched with each character a user types into the field. This can obviously generate a lot of overhead if the user types a lot of text or if something complex happens on the event, particularly if you are using Flash to communicate with a server and are attempting to send data back to the server. You can prevent problems associated with this much added overhead by not using either of these events. Instead, you can wait until the user finishes typing and deal with the text all at once by providing a button and using its click
event to call your event handler. This will be the preferred method of dealing with user-input text most of the time.
Note that users cannot enter or change text in dynamic text fields, although the text in dynamic fields can be selected and copied, unless you prevent the user from selecting
the text in a field by setting its selectable property to false
.
Any block of text in ActionScript is an instance of the String
class. The class contains a set of methods that enable you to work with and manipulate the text.
Some of the most useful of these methods allow you to find particular pieces of text within a string. If you want to return a character from a particular location within the string, you can use charAt()
. For example, examine this code:
var userName: String = "Mal Reynolds"; trace(userName.charAt(4));
The trace
statement would display R
. Note that the method begins counting in the string at zero for the first character, not one; hence the R is at index 4, not 5.
You can find out where a particular character exists in a string with the indexOf()
method. Using the same example string as above, userName.indexOf("a")
would return 1, after finding the first A as the second character. Note that like charAt(), indexOf()
counts from zero and as such essentially returns the length of the string up to the found character. The related lastIndexOf()
method performs the same task but looks at the string from right to left and thus finds the last instance of the character rather than the first.
If indexOf()
does not find the string, it returns −1. This can be useful in determining whether or not a particular character exists in the string, for example —
var email:String = "malatserenity.com"; var validateEmail:Number = email.indexOf("@"); if (validateEmail != −1) { trace("Email is valid"); } else { trace("Email is invalid"); }
if
statements are covered in more detail in Chapter 11.
The String
class contains a single property, length
, which returns the number of characters in a string. For example, consider this code:
var pilot:String = "Hoban Washburne"; var stringLength:Number = pilot.length;
The value of the stringLength
variable would be 15. Note that all characters in the string, including spaces, are counted.
You can convert the string to use specific capitalization using the toLowerCase()
and toUpperCase() methods. Given the pilot variable above, pilot.toLowerCase()
would return hoban washburne, and pilot.toUpperCase()
would return HOBAN WASHBURNE. The ActionScript documentation notes that there is also a toLocaleLowerCase()
method that is intended to be locale-specific, but the language actually treats it the same as toLowerCase()
. This also applies to the toLocaleUpperCase()
method, which functions just like toUpperCase()
.
The String
class also contains a concat()
method. Normally, concatenation can be performed on strings by simply using the + operator, so firstName
and lastName
strings could be combined into a single fullName
string, including a space, with var fullName: String = firstName + " " + lastName
. The concat()
function does essentially the same thing: var fullName:String = firstName.concat(" ", lastName)
;. There is no functional difference between these two approaches.
There is some potential confusion when you use indexOf(), lastIndexOf()
, or charAt()
to find the final character in the string and then compare it to the length
property. Because the methods begin counting with the first character of the string as zero, indexOf()
for the final character in the string will be one less than the length:
var mechanic:String = "Kaylee Frye"; var lastCharacter:Number = mechanic.lastIndexOf("e"); var length:Number = mechanic.length; trace(lastCharacter) //returns 10; trace(length) //returns 11;
You may find situations in which you need to break strings into smaller component strings. For example, if you have an email address, you may want to separate the username, which precedes the @ sign, from the domain name, which follows the symbol.
ActionScript contains two closely related methods for extracting pieces of strings: substr()
and substring()
. The first method, substr()
, takes two arguments: the starting index from which to extract the string and the number of characters to extract. For example, consider the following:
var doctor:String = "Simon Tam"; var stringPart: String = doctor.substr(2, 3);
The variable stringPart
would then equal mon:
the three characters starting with the third character. Note here that the third character has an index of 2, just as if you had used doctor.indexOf("m")
.
The substring()
function also takes two arguments. The first, just as with substr()
, indicates the index at which to begin extracting the string. The second argument, however, is also an index — the index of the character after which the extraction should end. Therefore, using the same example string from above, doctor.substring(6,8)
would return Tam — the characters beginning at index 6, or the seventh character in the string, and ending just at index 8, or the ninth character.
ActionScript also supports the slice()
method. This method is very similar to substring()
, and in fact when given positive numbers as its arguments, it is identical. However, the slice()
method also accepts negative arguments, in which case it searches the string right-to-left, whereas a negative value passed to substring()
is ignored and causes it to default to 0:
var muscle:String = "Jayne Cobb"; trace(muscle.substring(6, muscle.length); //returns "Cobb" trace(muscle.slice(6, muscle.length); //returns "Cobb" trace(muscle.substring(-3, muscle.length); // returns "Jayne Cobb" trace(muscle.slice(-3, muscle.length); // returns "Cobb"
Text fields can display only strings. If you attempt to put any other type of data into a text field, a runtime error will occur. For example, this code will result in an error:
txtNumberOfCharacters.text = userName.length;
If you run this code, the Compiler Errors panel will appear and display "1067: Implicit coercion of a value of type int to an unrelated type String
." This error is the result of trying to put a numeric value — the value of the length
property — into a text field. You can avoid this error by explicitly converting the offending value to a string. Therefore, modifying the code as follows will succeed:
txtNumberOfCharacters.text = String(userName.length);
The same runtime error will occur if you try to put any other data type into a text field, including Booleans. The solution is the same: Pass the Boolean value to String()
.
Occasionally, automatic type conversion will occur. For example, if you concatenate a number and a string, the result will be converted to a string, which can be placed directly into a text field. Therefore, txtResult.text = "The result is " + (5 + 4)
will work without you needing to explicitly convert the mathematical expression to a string.
Flash Player opens.
If you do not see the Compiler Errors panel, it may be behind Flash Player or the Actions panel.
Note that complex data types, such as MovieClips
and Arrays
, cannot be simply converted to strings. Passing a complex type to String()
will not return an error, however. The classes that define those complex types contain a special method, to String()
, which is automatically invoked when you attempt to use them as a string. This method returns a message about the data type, so for example, attempting to put a MovieClip
directly into a text field will result in [object MovieClip] appearing in the field.
Technically, String()
is not a method but is rather the constructor for the String
class. Therefore, the line String(userName.length)
is actually creating a new string from the variable.
3.137.172.68