Recipe 8.2 Creating a Text Field

8.2.1 Problem

You want to create a text field at runtime that you can use in your Flash movie.

8.2.2 Solution

You can create a text field using the MovieClip.createTextField( ) method.

8.2.3 Discussion

You can create a text field at authoring time using Flash's Text tool. Manual creation lets you see the layout of the objects on the Stage. However, many projects benefit from creating text fields dynamically. For example:

  • An animation with randomized text elements

  • A user interface in which items (and their labels) are created dynamically based on data loaded into the movie from a text file, XML document, or other source

  • A form that automatically adapts to a user's input

  • Word games

The MovieClip.createTextField( ) method creates a text field at runtime. Note that the createTextField( ) method is invoked on a MovieClip object, not a text field. (If we had a text field already, we wouldn't need the recipe, now would we?)

The createTextField( ) method takes six required parameters:

parentMovieClip.createTextField(name, depth, x, y, width, height);

where the parameters are as follows:

name

The instance name of the new text field

depth

The depth (within the MovieClip object) of the new text field

x

The x position relative to parentMovieClip's registration point

y

The y position relative to parentMovieClip's registration point

width

The width of the field in pixels

height

The height of the field in pixels

The new text field is created within the movie clip from which the method is invoked, which is called the parent clip or container clip.

This example creates a new text field named myText with a depth of 1, positioned at (0, 0), and with a width of 100 and a height of 20 within _root:

_root.createTextField("myText", 1, 0, 0, 100, 20);

Once the text field is created, it can be targeted using parentMovieClip.newTextFieldName, as follows:

_root.myText._x = 100;

The parent clip can be _root (the main timeline) or a movie clip created either at runtime or authoring time. You can use the duplicateMovieClip( ), attachMovie( ), and createEmptyMovieClip( ) methods of the MovieClip class to dynamically create a parent movie clip to hold the text field:

_root.createEmptyMovieClip("myTextHolder", 1); _root.myTextHolder.createTextField("myText", 1, 0, 0, 100, 20); _root.myTextHolder.myText.text = "This is a new text object";

You can remove a TextField created with createTextField( ) simply by invoking the removeTextField( ) method on that object, as follows:

myText.removeTextField(  );

8.2.4 See Also

Recipe 7.11



ActionScript Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2005
Pages: 425

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net