User Guide
46 Chapter 3: Working with Components
Adding components at runtime with ActionScript
Use the
createClassObject() method (which most components inherit from the UIObject
class) to add components to a Flash application dynamically. For example, you could add
components that create a page layout based on user-set preferences (as on the home page of a
web portal).
Version 2 components that are installed with Flash MX 2004 reside in package directories. (For
more information, see “Using packages” in Using ActionScript in Flash.) If you add a component
to the Stage during authoring, you can refer to the component simply by using its instance name
(for example,
myButton). However, if you add a component to an application with ActionScript
(at runtime), you must either specify its fully qualified class name (for example,
mx.controls.Button) or import the package by using the import statement.
For example, to write ActionScript code that refers to an Alert component, you can use the
import statement to reference the class, as follows:
import mx.controls.Alert;
Alert.show("The connection has failed", "Error");
Alternatively, you can use the full package path, as follows:
mx.controls.Alert.show("The connection has failed", "Error");
For more information, see “Importing classes” in Using ActionScript in Flash.
You can use ActionScript methods to set additional parameters for dynamically added
components. For more information, see Chapter 6, “Components Dictionary,” on page 91.
To add a component to a document at runtime, it must be in the library when the SWF file is
compiled. To add a component to the library, add it to the Stage and delete it.
Note: The instructions in this section assume an intermediate or advanced knowledge
of ActionScript.
To add a component to your Flash document using ActionScript:
1.
Drag a component to the Stage and delete it.
If you do this, you must select the Export in First Frame check box in the Linkage Properties
dialog box of the component in the library.
Note: If a component is set to Export in First Frame, you can’t preload the component.
2.
Select the frame in the Timeline where you want to add the component.
3.
Open the Actions panel if it isn’t already open.
4.
Call createClassObject() to create the component instance at runtime.
This method can be called on its own, or from any component instance. The
createClassObject() method takes the following parameters: a component class name, an
instance name for the new instance, a depth, and an optional initialization object that you can
use to set properties at runtime.
You can specify the class package in the class name parameter, as in this example:
createClassObject(mx.controls.CheckBox, "cb", 5, {label:"Check Me"});