What is Software? | What is Education? | What is Technology? | What is Research? | What is Wi-Fi? | What is Communication? | What is Customer Service?

Free SEO Tutorials & Help

Tutorials:   Adobe Flash   Adobe Photoshop   CorelDRAW   SEO  

Site Map

Website Development | Cable & Broadband Magazine | Solutions for Higher Education | Auction Anything Online

Adobe Flash Help & Tutorials

 Back to Topics

 

How to Create Components in Flash

Component source files

Overview of component structure

Building your first component

Creating the Dial Flash (FLA) file

Creating the Dial class file

Testing and exporting the Dial component

Selecting a parent class

Creating a component movie clip

Creating the ActionScript class file

Importing classes

Identifying the class, symbol, and owner names

Defining variables

Using getter/setter methods to define parameters

Adding component metadata

Metadata tags

About the Inspectable tag

About the InspectableList tag

About the Event tag

About the Bindable tag

About the ChangeEvent tag

About the Collection tag

About the ComponentTask tags

Defining component parameters

About core functions

Defining the init() method

Defining the createChildren() method

About the constructor function

Defining the draw() method

Defining the size() method

Dispatching events

About assigning skins

About styles

Incorporating existing components within your component

Creating the LogIn Flash (FLA) file

The LogIn class file

Testing and exporting the LogIn component

Exporting and distributing a component

Understanding SWC files

Exporting SWC files

Importing component SWC files into Flash

Final steps in component development

Component development checklist

Component source files

TOP

The components available in the Components panel are precompiled SWC clips. The source Flash Document (FLA) containing the graphics and the source ActionScript class files (AS) containing the code for these components have also been provided for you to use in creating your own custom components. The source files for the version 2 components are installed with Macromedia Flash. It is helpful to open and review a few of these files, and try to understand their structure before you build your own components. The RadioButton component is a good example of a simpler component that you may want to explore first. All the components are symbols in the library of StandardComponents.fla. Each symbol is linked to an ActionScript class.

 

Overview of component structure

TOP

A component consists of a Flash (FLA) file and an ActionScript (AS) file. You can optionally create and package other files (for example, an icon and a .swd debugging file) with your component, but all components require a FLA and an ActionScript file. When you've finished developing your component, you export it as a SWC file.



A Flash (FLA) file, an ActionScript (AS) file, and a SWC file


The FLA file contains a movie clip symbol that must be linked to the AS file in both the Linkage Properties and the Component Definition dialog boxes.

The movie clip symbol has two frames and two layers. The first layer is an Actions layer and has a stop() global function on Frame 1. The second layer is an Assets layer with two keyframes: Frame 1 contains a bounding box; Frame 2 contains all other assets, including graphics and base classes, used by the component.



The ActionScript code specifying the properties and methods for the component is in a separate ActionScript class file. This class file also declares which, if any, classes the component extends. The name of the AS class file is the name of the component plus the ".as" extension. For example, MyComponent.as contains the source code for the MyComponent component.

It's a good idea to save the component's FLA and AS files in the same folder and give them the same name. If the AS file is not saved in the same folder, you must verify that the folder is in the classpath so the FLA file can find it. For more information about the classpath, see Classes in Learning ActionScript 2.0 in Flash.

 
Building your first component

TOP

In this section, you will build a Dial component. The completed component files, Dial.fla, Dial.as, and DialAssets.fla are located in the examples folder on your computer:

The Dial component is a potentiometer, like those used to measure potential difference in voltage. A user can click on the needle and drag it to change its position. The API for the Dial component has one property, value, that you can use to get and set the position of the needle.

This section takes you through the steps of creating a component. These procedures are discussed in more detail in subsequent sections (including Selecting a parent class, Creating a component movie clip, Creating the ActionScript class file, and Exporting and distributing a component).This section contains the following topics:

  • Creating the Dial Flash (FLA) file

  • Creating the Dial class file

  • Testing and exporting the Dial component
     

Creating the Dial Flash (FLA) file

TOP

The first steps for creating a component include creating the component movie clip within a FLA document file.

To create the Dial FLA file:

  1. In Flash, select File > New and create a new document.

  2. Select File > Save As and save the file as Dial.fla.

    The file can have any name, but giving it the same name as the component is practical.

  3. Select Insert > New Symbol. The component itself is created as a new MovieClip symbol so it will be available through the library.

    Name the component Dial, and assign it the behavior Movie clip.

  4. If the Linkage section of the Create New Symbol dialog box isn't open, click the Advanced button to reveal it.

  5. In the Linkage area, select Export for ActionScript and deselect Export in First Frame.

  6. In the Identifier text box, enter a linkage identifier such as Dial_ID.

  7. in the AS 2.0 Class text box, enter Dial. This value is the component class name. If the class is in a package (for example, mx.controls.Button), enter the entire package name.

  8. Click OK.

    Flash changes to symbol-editing mode.

  9. Insert a new layer. Name the top layer Actions and the bottom layer Assets.

  10. Select Frame 2 in the Assets layer and insert a keyframe (F6).

    This is the structure of the component movie clip: an Actions layer and an Assets layer. The Actions layer has one keyframe and the Assets layer has two keyframes.

  11. Select Frame 1 in the Actions layer and open the Actions panel (F9). Enter a stop(); global function.

    This prevents the movie clip from proceeding to Frame 2.

  12. Select File > Import > Open External Library and select the StandardComponents.fla file from the Configuration/ComponentFLA folder. For example:

    NOTE : For information about folder locations, see Configuration folders installed with Flash in Getting Started with Flash.

  13. Dial extends the UIComponent base class; therefore, you must drag an instance of the UIComponent into the Dial document. In the StandardComponents.fla library, browse to the UIComponent movie clip in the following folder: Flash UI Components 2 > Base Classes > FUIObject Subclasses and drag it to the Dial.fla library.

    Asset dependencies are automatically copied to the Dial library with UIComponent.

    NOTE : When you drag UIComponent to the Dial library, the folder hierarchy in the Dial library is changed. If you plan to use your library again, or use it with other groups of components (such as the version 2 components), you should restructure the folder hierarchy to match the StandardComponents.fla library so that it's organized well and you avoid duplicate symbols.

  14. In the Assets layer, select Frame 2 and drag an instance of UIComponent to the Stage.

  15. Close the StandardComponents.fla library.

  16. Select File > Import > Open External Library and select the DialAssets.fla file.

  17. In the Assets layer, select Frame 2 and drag an instance of the DialFinal movie clip from the DialAssets library to the Stage.

    All the component assets are added to Frame 2 of the Assets layer. Because Frame 1 of the Actions layer has a stop() global function, the assets in Frame 2 will not be seen as they are arranged on the Stage.

    You add assets to Frame 2 for two reasons:

    • So that all assets and sub assets are automatically copied into the library and are available to instantiate dynamically (in the case of DialFinal), or to access their methods, properties, and events (in the case of UIComponent).

    • Placing assets in a frame ensures that they are loaded more smoothly as the movie is streamed, so you don't need to set the library assets to export in the first frame. This approach prevents an initial spike of data transfer while downloading.

  18. Close the DialAssets.fla library.

  19. In the Assets layer, select Frame 1. Drag the BoundingBox movie clip from the library (Flash UI Components 2 > Component Assets folder) to the Stage. Name the BoundingBox instance boundingBox_mc. Use the Info panel to set both the height and width of the DialFinal movie clip to 250 pixels, and the x, y coordinates at 0, 0.

    The BoundingBox instance is used to create the component's live preview and resize during authoring. You must set the size of the bounding box so that it can enclose all the graphical elements in your component.

    NOTE : If you are extending a component (including any version 2 component) you must keep any instance names already in use by that component because its code will refer to those instance names. For example, if you include a version 2 component that is already using the instance name boundingBox_mc, you should not rename it. For your own instance names, you can use any unique name that does not conflict with an existing one within the same scope.

  20. Select the Dial movie clip in the library, and select Component Definition from the Library context menu (Windows: Right-click; Mac: control-click).

  21. In the AS 2.0 Class text box, enter Dial.

    This value is the name of the ActionScript class. If the class is in a package, the value is the full package, for example, mx.controls.CheckBox.

  22. Click OK.

  23. Save the file.

 

Creating the Dial class file

TOP

Now, you need to create the Dial class file as a new ActionScript file.

To create the Dial class file:

  1. In Flash, select File > New and then select ActionScript File.

  2. Select File > Save As and save the file as Dial.as in the same folder as the Dial.fla file.

    NOTE : You can use any text editor to save the Dial.as file.

  3. You can copy or type the following Dial component ActionScript class code into your new Dial.as file. Typing rather than copying the code helps you become familiar with each element of the component code.

Please read the comments in the code for a description of each section. (For detailed information on the elements of a component class file, see Overview of a component class file.

// Import the package so you can reference

// the class directly.

import mx.core.UIComponent;

// Event metadata tag

[Event("change")]

class Dial extends UIComponent

{

// Components must declare these to be proper

// components in the components framework.

static var symbolName:String = "Dial";

static var symbolOwner:Object = Dial;

var className:String = "Dial";
 

// The needle and dial movie clips that are

// the component's graphical representation

private var needle:MovieClip;

private var dial:MovieClip;

private var boundingBox_mc:MovieClip;

// The private member variable "__value" is publicly

// accessible through implicit getter/setter methods,

// Updating this property updates the needle's position

// when the value is set.

private var __value:Number = 0;

// This flag is set when the user drags the

// needle with the mouse, and cleared afterwards.

private var dragging:Boolean = false;

// Constructor;

// While required for all classes, v2 components require

// the contstructor to be empty with zero arguments.

// All initialization takes place in a required init()

// method after the class instance has been constructed.

function Dial() {

}

// Initialization code:

// The init() method is required for v2 components. It must also

// in turn call its parent class init() method with super.init().

// The init() method is required for components extending UIComponent.

function init():Void {

super.init();

useHandCursor = false;

boundingBox_mc._visible = false;

boundingBox_mc._width = 0;

boundingBox_mc._height = 0;

}

// Create children objects needed at start up:

// The createChildren() method is required for components

// extending UIComponent.

public function createChildren():Void {

dial = createObject("DialFinal", "dial", 10);

size();

}

// The draw() method is required for v2 components.

// It is invoked after the component has been

// invalidated by someone calling invalidate().

// This is better than redrawing from within the set() function

// for value, because if there are other properties, it's

// better to batch up the changes into one redraw, rather

// than doing them all individually. This approach leads

// to more efficiency and better centralization of code.

function draw():Void {

super.draw();

dial.needle._rotation = value;

}

// The size() method is invoked when the component's size

// changes. This is an opportunity to resize the children,

// and the dial and needle graphics.

// The size() method is required for components extending UIComponent.

function size():Void {

super.size();

dial._width = width;

dial._height = height;

// Cause the needle to be redrawn, if necessary.

invalidate();

}

// This is the getter/setter for the value property.

// The [Inspectable] metadata makes the property appear

// in the Property inspector. This is a getter/setter

// so that you can call invalidate and force the component

// to redraw, when the value is changed.

[Bindable]

[ChangeEvent("change")]

[Inspectable(defaultValue=0)]

function set value (val:Number)

{

__value = val;

invalidate();

}

function get value ():Number

{

return twoDigits(__value);

}

function twoDigits(x:Number):Number

{

return (Math.round(x * 100) / 100);

}


// Tells the component to expect mouse presses

function onPress()

{

beginDrag();

}

// When the dial is pressed, the dragging flag is set.

// The mouse events are assigned callback functions.

function beginDrag()

{

dragging = true;

onMouseMove = mouseMoveHandler;

onMouseUp = mouseUpHandler;

}

// Remove the mouse events when the drag is complete

// and clear the flag.

function mouseUpHandler()

{

dragging = false;

delete onMouseMove;

delete onMouseUp;

}

function mouseMoveHandler()

{

// Calculate the angle

if (dragging) {

var x:Number = _xmouse - width/2;

var y:Number = _ymouse - height/2;

var oldValue:Number = value;

var newValue:Number = 90+180/Math.PI*Math.atan2(y, x);\

if (newValue<0) {

newValue += 360;

}

if (oldValue != newValue) {

value = newValue;

dispatchEvent( {type:"change"} );

}

}

}

}

 

Testing and exporting the Dial component

TOP

You've created the Flash file that contains the graphical elements, the base classes and the class file that contains all the functionality of the Dial component. Now it's time to test the component.

Ideally, you would test the component as you work, especially while you're writing the class file. The fastest way to test as you work is to convert the component to a compiled clip and use it in the component's FLA file.

When you've completely finished a component, export it as a SWC file. For more information, see Exporting and distributing a component.

To test the Dial component:

  1. In the Dial.fla file, select the Dial component in the library, open the Library context menu (Windows: Right-click; Mac: control-click), and select Convert to Compiled Clip.

    A compiled clip is added to the library with the name Dial SWF.

    NOTE : If you've already created a compiled clip (for example, if this is the second or third time you're testing), a Resolve Library Conflict dialog box appears. Select Replace Existing Items to add the new version to the document.

  2. Drag Dial SWF to the Stage on the main Timeline.

  3. You can resize it and set its value property in the Property inspector or the Component Inspector. When you set its value property, the needle's position should change accordingly.

  4. To test the value property at runtime, give the dial the instance name dial and add the following code to Frame 1 on the main Timeline:

    // position of the text field

    var textXPos:Number = dial.width/2 + dial.x

    var textYPos:Number = dial.height/2 + dial.y;

    // creates a text field in which to view the dial.value

    createTextField("dialValue", 10, textXPos, textYPos, 100, 20);

    // creates a listener to handle the change event

    function change(evt){

    // places the value property in the text field

    // whenever the needle moves

    dialValue.text = dial.value;

    }

    dial.addEventListener("change", this);

    Select Control > Test Movie to test the component in Flash Player.

To export the Dial component:

  1. In the Dial.fla file, select the Dial component in the library, open the Library context menu (Windows: Right-click; Mac: control-click), and select Export SWC File.

  2. Select a location to save the SWC file.

If you save it to the Components folder in the user-level configuration folder, you can reload the Components panel without restarting Flash and the component appears in the panel.

NOTE : For information about folder locations, see Configuration folders installed with Flash in Using Flash.



The completed Dial component
 

Selecting a parent class

TOP

The first thing to decide when creating a component is whether to extend one of the version 2 classes. If you choose to extend a version 2 class, you can either extend a component class (for example, Button, CheckBox, ComboBox, List, and so on) or one of the base classes, UIObject or UIComponent. All the component classes, except the Media components, extend the base classes; if you extend a component class, the class automatically inherits from the base classes as well.

The two base classes supply common features for components. By extending these classes, your component begins with a basic set of methods, properties, and events.

You don't have to create a subclass UIObject or UIComponent or any other classes in the version 2 framework. Even if your component classes inherit directly from the MovieClip class, you can use many powerful component features: export to a SWC file or compiled clip, use built-in live preview, view inspectable properties, and so on. However, if you want your components to work with the Macromedia version 2 components, and use the manager classes, you need to extend UIObject or UIComponent.

The following table briefly describes the version 2 base classes:

 

Base class

Extends

Description

mx.core.UIObject

MovieClip

UIObject is the base class for all graphical objects. It can have shape, draw itself, and be invisible.

UIObject provides the following functionality:

  • Editing styles

  • Event handling

  • Resizing by scaling

mx.core.UIComponent

UIObject

UIComponent is the base class for all components.

UIComponent provides the following functionality:

  • Creating focus navigation

  • Creating a tabbing scheme

  • Enabling and disabling components

  • Resizing components

  • Handling low-level mouse and keyboard events


Understanding the UIObject class

Components based on version 2 of the Macromedia Component Architecture descend from the UIObject class, which is a subclass of the MovieClip class. The MovieClip class is the base class for all classes in Flash that represent visual objects on the screen.

UIObject adds methods that allow you to handle styles and events. It posts events to its listeners just before drawing (the draw event is the equivalent of the MovieClip.onEnterFrame event), when loading and unloading (load and unload), when its layout changes (move, resize), and when it is hidden or revealed (hide and reveal).

UIObject provides alternate read-only variables for determining the position and size of a component (width, height, x, y), and the move() and setSize() methods to alter the position and size of an object.

The UIObject class implements the following:

  • Styles

  • Events

  • Resize by scaling

Understanding the UIComponent class

The UIComponent class is a subclass of UIObject (see UIComponent class in Components Language Reference). It is the base class of all components that handle user interaction (mouse and keyboard input). The UIComponent class allows components to do the following:

  • Receive focus and keyboard input

  • Enable and disable components

  • Resize by layout

About extending other version 2 classes

To make component construction easier, you can extend any class; you are not required to extend the UIObject or UIComponent class directly. If you extend any other version 2 component's class (except the Media components), you extend UIObject and UIComponent by default. Any component class listed in the Component dictionary can be extended to create a new component class.

For example, if you want to create a component that behaves almost the same as a Button component does, you can extend the Button class instead of re-creating all the functionality of the Button class from the base classes.

The following figure shows the version 2 component hierarchy:



Version 2 component hierarchy

A FlashPaper version of this file is available in the Flash installation directory at this location: Flash 8\Samples and Tutorials\Samples\Components\arch_diagram.swf.

About extending the MovieClip class

You can choose not to extend a version 2 class and have your component inherit directly from the ActionScript MovieClip class. However, if you want any of the UIObject and UIComponent functionality, you'll have to build it yourself. You can open the UIObject and UIComponent classes (First Run/Classes/mx/core) to examine how they are constructed.
 

Creating a component movie clip

TOP

To create a component, you must create a movie clip symbol and link it to the component's class file.

The movie clip has two frames and two layers. The first layer is an Actions layer and has a stop() global function on Frame 1. The second layer is an Assets layer with two keyframes. Frame 1 contains a bounding box or any graphics that serve as placeholders for the final art. Frame 2 contains all other assets, including graphics and base classes, used by the component.

Inserting a new movie clip symbol

All components are MovieClip objects. To create a new component, you must first insert a new symbol into a new FLA file.

To add a new component symbol:

  1. In Flash, create a blank Flash document.

  2. Select Insert > New Symbol.

    The Create New Symbol dialog box appears.

  3. Enter a symbol name. Name the component by capitalizing the first letter of each word in the component (for example, MyComponent).

  4. Select the Movie Clip behavior.

  5. Click the Advanced button to display the advanced settings.

  6. Select Export for ActionScript and deselect Export in First Frame and Export in First Frame.

  7. Enter a linkage identifier.

  8. In the AS 2.0 Class text box, enter the fully qualified path to the ActionScript 2.0 class.

    The class name should be the same as the component name that appears in the Components panel. For example, the Button component's class is mx.controls.Button.

    NOTE : Do not include the filename's extension; the AS 2.0 Class text box points to the packaged location of the class and not the file system's name for the file.

    If the ActionScript file is in a package, you must include the package name. This value can be relative to the classpath or can be an absolute package path (for example, mypackage.MyComponent).

  9. In most cases, you should deselect Export in First Frame (it is selected by default). For more information, see Component development checklist.

  10. Click OK.

Flash adds the symbol to the library and switches to symbol-editing mode. In this mode, the name of the symbol appears above the upper-left corner of the Stage, and a cross hair indicates the symbol's registration point.

You can now edit the symbol to create a component. See Editing the movie clip.

Editing the movie clip

After you create the new symbol and define the linkages for it, you can define the component's assets in the symbol's Timeline.

A component's symbol should have two layers. This section describes what layers to insert and what to add to those layers.

To edit the movie clip:

  1. Rename Layer 1 Actions and select Frame 1.

  2. Open the Actions panel and add a stop() function, as follows:

    stop();

    Do not add any graphical assets to this frame.

  3. Add a Layer named Assets.

  4. On the Assets layer, select Frame 2 and insert a blank keyframe.

    There are now two blank keyframes in this layer.

  5. Do one of the following:

    • If the component has visual assets that define the bounding area, drag the symbols into Frame 1 and arrange them appropriately.

    • If your component creates all its visual assets at runtime, drag a BoundingBox symbol to the Stage in Frame 1, size it correctly, and name the instance boundingBox_mc. The symbol is located in the library of the StandardComponents.fla that is located in the Configuration/ComponentFLA folder.

  6. If you are extending an existing component, place an instance of that component and any other base classes in Frame 2 of the Assets layer.

    To do this, select the symbol from the Components panel and drag it to the Stage. If you are extending a base class, open StandardComponents.fla from the Configuration/ComponentFLA folder and drag the class from the library to the Stage.

    NOTE : When you drag UIComponent to the component library, the folder hierarchy in the library is changed. If you plan to use your library again, or use it with other groups of components (such as the version 2 components), you should restructure the folder hierarchy to match the StandardComponents.fla library so that it's organized well and you avoid duplicate symbols.

  7. Add any graphical assets used by this component on Frame 2 of your component's Assets layer.

    Any asset that a component uses (whether it's another component or media such as bitmaps) should have an instance placed in the second frame of the Assets layer.\

  8. Your finished symbol should look something like this:



    Defining the movie clip as a component

The movie clip symbol must be linked to an ActionScript class file in the Component Definition dialog box. This is how Flash knows where to look for the component's metatags. (For more information about metatags, see Adding component metadata.) There are other options you can select in the Component Definition dialog box as well.

To define a movie clip as a component:

  1. Select the movie clip in the library and select Component Definition from the Library context menu (Windows: Right-click; Mac: control-click).

  2. You must enter an AS 2.0 class.

    If the class is part of a package, enter the full package name.

  3. Specify other options in the Component Definition dialog box, if desired:

  • Click the Plus (+) button to define parameters.

This is optional. The best practice is to use the metadata Inspectable tag in the component's class file to specify parameters. When an ActionScript 2.0 class is not specified, define the parameters for the component here.

  • Specify a custom UI.

This is a SWF file that plays in the Component inspector. You can embed it in the component FLA file or browse to an external SWF.

  • Specify a live preview.

This is an external or embedded SWF file. You don't need to specify a live preview here; you can add a bounding box to the component movie clip, and Flash creates a live preview for you.

See Creating a component movie clip.

  • Enter a description.

The Description field was deprecated in Flash MX 2004 because the Reference panel has been removed. This field is provided for backward compatibility when you save FLA files in the Flash MX format.

  • Choose an icon.

    This option specifies a PNG file to use as an icon for the component. If you specify an IconFile metadata tag in the ActionScript 2.0 class file (best practice), this field is ignored.

  • Select or deselect Parameters Are Locked in Instances.

    When this option is unselected, users can add parameters to each component instance that differ from the component's parameters. Generally, this setting should be selected. This option provides backward compatibility with Flash MX.

  • Specify a tooltip that appears in the Components panel.
     

Creating the ActionScript class file

TOP

 
All component symbols are linked to an ActionScript 2.0 class file. (For information on linking, see Creating a component movie clip.)

To edit ActionScript class files, you can use Flash, any text editor, or any Integrated Development Environment (IDE).

The external ActionScript class extends another class (whether the class is a version 2 component, a version 2 base class, or the ActionScript MovieClip class). You should extend the class that creates the functionality that is most similar to the component you want to create. You can inherit from (extend) only one class. ActionScript 2.0 does not allow multiple inheritance.

This section contains the following topics:

  • Simple example of a component class file
  • Overview of a component class file
  • Defining the class and its superclass
  • Identifying the class, symbol, and owner names
  • Defining variables
  • Using getter/setter methods to define parameters
  • Adding component metadata
  • Defining component parameters
  • About core functions
  • Dispatching events
  • About assigning skins
  • About styles

Simple example of a component class file

The following is a simple example of a class file called MyComponent.as. If you were creating this component, you would link this file to the component movie clip in Flash.

This example contains a minimal set of imports, methods, and declarations for a component, MyComponent, that inherits from the UIComponent class. The MyComponents.as file is saved in the myPackage folder.

[Event("eventName")]

// Import packages.

import mx.core.UIObject;

// Declare the class and extend from the parent class.

class mypackage.MyComponent extends UIObject {

// Identify the symbol name that this class is bound to.

static var symbolName:String = "mypackage.MyComponent";

// Identify the fully qualified package name of the symbol owner.

static var symbolOwner:Object = Object(mypackage.MyComponent);

// Provide the className variable.

var className:String = "MyComponent";

// Define an empty constructor.

function MyComponent() {

}

// Call the parent's init() method.

// Hide the bounding box--it's used

// only during authoring.

function init():Void {

super.init();

boundingBox_mc.width = 0;

boundingBox_mc.height = 0;

boundingBox_mc.visible = false;

}

function createChildren():Void{

// Call createClassObject to create subobjects.

size();

invalidate();

}

function size(){

// Write code to handle sizing.

super.size();

invalidate();

}

function draw(){

// Write code to handle visual representation.

super.draw();

}

}

Overview of a component class file

The following is a general procedure that describes how to create an ActionScript file for a component class. Some steps may be optional, depending on the type of component you create.

To write a component class file:

  1. (Optional) Import classes. (See Importing classes).

    This allows you to refer to classes without writing out the package (for example, Button instead of mx.controls.Button).

  2. Define the class using the class keyword; use the extend keyword to extend a parent class. (See Defining the class and its superclass).
  3. Define the symbolName, symbolOwner, and className variables. (See Identifying the class, symbol, and owner names).

    These variables are necessary only in version 2 components.

  4. Define member variables. (See Defining variables).

    These can be used in getter/setter methods.

  5. Define a constructor function. (See About the constructor function).
  6. Define an init() method. (See Defining the init() method).

    This method is called when the class is created if the class extends UIComponent. If the class extends MovieClip, call this method from the constructor function.

  7. Define a createChildren() method. (See Defining the createChildren() method).

    This method is called when the class is created if the class extends UIComponent. If the class extends MovieClip, call this method from the constructor function.

  8. Define a size() method. (See Defining the size() method).

    This method is called when the component is resized, if the class extends UIComponent. In addition, this method is called when the component's live preview is resized during authoring.

  9. Define a draw() method. (See About invalidation).

    This method is called when the component is invalidated, if the class extends UIComponent.

  10. Add a Metadata tag and declaration. (See Adding component metadata).

    Adding the tag and declaration causes getter/setter properties to appear in the Property inspector and Component inspector in Flash.

  11. Define getter/setter methods. (See Using getter/setter methods to define parameters).
  12. (Optional) Create variables for every skin element/linkage used in the component. (See About assigning skins).

This allows users to set a different skin element by changing a parameter in the component.

 

Importing classes

TOP

You can import class files so that you don't have to write fully qualified class names throughout your code. This can make code more concise and easier to read. To import a class, use the import statement at the top of the class file, as in the following:

import mx.core.UIObject;

import mx.core.ScrollView;

import mx.core.ext.UIObjectExtensions;

class MyComponent extends UIComponent{

You can also use the wildcard character (*) to import all the classes in a given package. For example, the following statement imports all classes in the mx.core package:

import mx.core.*;

If an imported class is not used in a script, the class is not included in the resulting SWF file's bytecode. As a result, importing an entire package with a wildcard does not create an unnecessarily large SWF file.

 

Identifying the class, symbol, and owner names

TOP

ATo help Flash find the proper ActionScript classes and packages and to preserve the component's naming, you must set the symbolName, symbolOwner, and className variables in your component's ActionScript class file.

The symbolOwner variable is an Object reference that refers to a symbol. If the component is its own symbolOwner or is the symbolOwner has been imported, it does not have to be fully qualified.

The following table describes these variables:
 

Variable

Type

Description

symbolName

String

The name of the ActionScript class (for example, ComboBox).

This name must match the symbol's linkage identifier.

This variable must be static.

symbolOwner

Object

The fully qualified class name (for example, mypackage.MyComponent).

Do not use quotation marks around the symbolOwner value, because it is an Object data type.

This name must match the AS 2.0 class in the Linkage Properties dialog box.

This variable is used in the internal call to the createClassObject() method.

This variable must be static.

className

String

The name of the component class. This does not include the package name and has no corresponding setting in the Flash development environment.

You can use the value of this variable when setting style properties.


The following example adds the symbolName, symbolOwner, and className variables to the MyButton class:

class MyButton extends mx.controls.Button {

static var symbolName:String = "MyButton";

static var symbolOwner = myPackage.MyButton;

var className:String = "MyButton";

}

 

Defining variables

TOP

The following code sample is from Button.as file (mx.controls.Button). It defines a variable, btnOffset, to use in the class file. It also defines the variables __label, and __labelPlacement. The latter two variables are prefixed with a double underscore to prevent name conflicts when they are used in getter/setter methods, and ultimately used as properties and parameters in the component. For more information, see Using getter/setter methods to define parameters in Learning ActionScript 2.0 in Flash.

/**

* Number used to offset the label and/or icon when button is pressed.

*/

var btnOffset:Number = 0;

/**

*@private

* Text that appears in the label if no value is specified.

*/

var __label:String = "default value";

/**

*@private

* default label placement

*/

var __labelPlacement:String = "right";

 

Using getter/setter methods to define parameters

TOP

The simplest way to define a component parameter is to add a public member variable that makes the parameter "inspectable." You can do this by using the Inspectable tag in the Component inspector, or adding the Inspectable variable as follows:

[Inspectable(defaultValue="strawberry")]

public var flavorStr:String;

However, if code that employs a component modifies the flavorStr property, the component typically must perform an action to update itself in response to the property change. For example, if flavorStr is set to "cherry", the component might redraw itself with a cherry image instead of the default strawberry image.

For regular member variables, the component is not automatically notified that the member variable's value has changed.

Getter/setter methods are a straightforward way to detect changes to component properties. Instead of declaring a regular variable with var, declare getter/setter methods, as follows:

private var __flavorStr:String = "strawberry";

[Inspectable(defaultValue="strawberry")]

public function get flavorStr():String{

return __flavorStr;

}

public function set flavorStr(newFlavor:String) {

__flavorStr = newFlavor;

invalidate();

}

The invalidate() call causes the component to redraw itself with the new flavor. This is the benefit of using getter/setter methods for the flavorStr property, instead of a regular member variable. See Defining the draw() method.

To define getter/setter methods, remember these points:

  • Precede the method name with get or set, followed by a space and the property name.

  • The variable that stores the property's value cannot have the same name as the getter or setter. By convention, precede the names of the getter and setter variables with two underscores.

Getters and setters are commonly used in conjunction with tags to define properties that are visible in the Property and Component inspectors. For more information, see Adding component metadata.

 

Adding component metadata

TOP

You can add component metadata tags in your external ActionScript class files to tell the compiler about component parameters, data binding properties, and events. Metadata tags are used in the Flash authoring environment for a variety of purposes.

The metadata tags can only be used in external ActionScript class files. You cannot use metadata tags in FLA files.

Metadata is associated with a class declaration or an individual data field. If the value of an attribute is a string, you must enclose that attribute in quotation marks.

Metadata statements are bound to the next line of the ActionScript file. When defining a component property, add the metadata tag on the line before the property declaration. The only exception is the Event metadata tag. When defining component events, add the metadata tag outside the class definition so that the event is bound to the entire class.

In the following example, the Inspectable tags define the flavorStr, colorStr, and shapeStr parameters:

[Inspectable(defaultValue="strawberry")]

public var flavorStr:String;

[Inspectable(defaultValue="blue")]

public var colorStr:String;

[Inspectable(defaultValue="circular")]

public var shapeStr:String;

In the Property inspector and the Parameters tab of the Component inspector, Flash displays all of these parameters as type String.

 

Metadata tags

TOP

The following table describes the metadata tags you can use in ActionScript class files:
 

Tag

Description

Inspectable

Exposes a property in the Component inspector and Property inspector. See About the Inspectable tag.

InspectableList

Identifies which subset of inspectable properties should be listed in the Property inspector and Component inspector. If you don't add an InspectableList attribute to your component's class, all inspectable parameters appear in the Property inspector. See About the InspectableList tag.

Event

Defines a component event. See About the Event tag.

Bindable

Reveals a property in the Bindings tab of the Component inspector. See About the Bindable tag.

ChangeEvent

Identifies a event that cause data binding to occur. See About the ChangeEvent tag.

Collection

Identifies a collection attribute exposed in the Component inspector. See About the Collection tag.

IconFile

Specifies the filename for the icon that represents this component in the Components panel. See About the IconFile tag.

ComponentTask

Specifies the filenames of one or more associated JSFL files to perform tasks in the authoring environment. See About the ComponentTask tag.

The following sections describe the component metadata tags in more detail.

 

About the Inspectable tag

TOP

You use the Inspectable tag to specify the user-editable (inspectable) parameters that appear in the Component inspector and Property inspector. This lets you maintain the inspectable properties and the underlying ActionScript code in the same place. To see the component properties, drag an instance of the component onto the Stage and select the Parameters tab of the Component inspector.

Collection parameters are also inspectable. For more information, see About the Collection tag.

The following figure shows the Parameters tab of the Component inspector for the DateChooser component:



Alternatively, you can view a subset of the component properties on the Property inspector Parameters tab.



When determining which parameters to reveal in the authoring environment, Flash uses the Inspectable tag. The syntax for this tag is as follows:

[Inspectable(value_type=value[,attribute=value,...])]

property_declaration name:type;

The following example defines the enabled parameter as inspectable:

[Inspectable(defaultValue=true, verbose=1, category="Other")]

var enabled:Boolean;

The Inspectable tag also supports loosely typed attributes like this:

[Inspectable("danger", 1, true, maybe)]

The metadata statement must immediately precede the property's variable declaration in order to be bound to that property.

The following table describes the attributes of the Inspectable tag:
 

Attribute

Type

Description

defaultValue

String or Number

(Optional) A default value for the inspectable property.

enumeration

String

(Optional) Specifies a comma-delimited list of legal values for the property.

listOffset

Number

(Optional) Added for backward compatibility with Flash MX components. Used as the default index into a List value.

name

String

(Optional) A display name for the property. For example, Font Width. If not specified, use the property's name, such as _fontWidth.

type

String

(Optional) A type specifier. If omitted, use the property's type. The following values are acceptable:

  • Array

  • Boolean

  • Color

  • Font Name

  • List

  • Number

  • Object

  • String

variable

String

(Optional) Added for backward compatibility with Flash MX components. Specifies the variable that this parameter is bound to.

verbose

Number

(Optional) An inspectable property that has the verbose attribute set to 1 does not appear in the Property inspector but does appear in the Component inspector. This is typically used for properties that are not modified frequently.


None of these attributes are required; you can use Inspectable as the metadata tag.

All properties of the superclass that are marked Inspectable are automatically inspectable in the current class. Use the InspectableList tag if you want to hide some of these properties for the current class.

 

About the InspectableList tag

TOP

Use the InspectableList tag to specify which subset of inspectable properties should appear in the Property inspector. Use InspectableList in combination with Inspectable so that you can hide inherited attributes for components that are subclasses. If you do not add an InspectableList tag to your component's class, all inspectable parameters, including those of the component's parent classes, appear in the Property inspector.

The InspectableList syntax is as follows:

[InspectableList("attribute1"[,...])]

// class definition

The InspectableList tag must immediately precede the class definition because it applies to the entire class.

The following example allows the flavorStr and colorStr properties to be displayed in the Property inspector, but excludes other inspectable properties from the Parent class:

[InspectableList("flavorStr","colorStr")]

class BlackDot extends DotParent {

[Inspectable(defaultValue="strawberry")]

public var flavorStr:String;

[Inspectable(defaultValue="blue")]

public var colorStr:String;

...

}

 

About the Event tag

TOP

PUse the Event tag to define events that the component emits.

This tag has the following syntax:

[Event("event_name")]

For example, the following code defines a click event:

[Event("click")]

Add the Event statements outside the class definition in the ActionScript file so that the events are bound to the class and not a particular member of the class.

The following example shows the Event metadata for the UIObject class, which handles the resize, move, and draw events:

...

import mx.events.UIEvent;

[Event("resize")]

[Event("move")]

[Event("draw")]

class mx.core.UIObject extends MovieClip {

...

}

To broadcast a particular instance, call the dispatchEvent() method. See Using the dispatchEvent() method.

 

About the Bindable tag

TOP

Data binding connects components to each other. You achieve visual data binding through the Bindings tab of the Component inspector. From there, you add, view, and remove bindings for a component.

Although data binding works with any component, its main purpose is to connect user interface components to external data sources, such as web services and XML documents. These data sources are available as components with properties, which you can bind to other component properties.

Use the Bindable tag before a property in an ActionScript class to make the property appear in the Bindings tab in the Component inspector. You can declare a property by using var or getter/setter methods. If a property has both a getter and a setter method, you only need to apply the Bindable tag to one.

The Bindable tag has the following syntax:

[Bindable "readonly"|"writeonly",type="datatype"]

Both attributes are optional.

The following example defines the variable flavorStr as a property that is accessible on the Bindings tab of the Component inspector:

[Bindable]

public var flavorStr:String = "strawberry";

The Bindable tag takes three options that specify the type of access to the property, as well as the data type of that property. The following table describes these options:
 

Option

Description

readonly

Indicates that when you create bindings in the Component inspector, you can only create bindings that use this property as a source. However, if you use ActionScript to create bindings, there is no such restriction.

[Bindable("readonly")]

writeonly

Indicates that when you create bindings in the Component inspector, this property can only be used as the destination of a binding. However, if you use ActionScript to create bindings, there is no such restriction.

[Bindable("writeonly")]

type="datatype"

Indicates the type that data binding uses for the property. The rest of Flash uses the declared type.

If you do not specify this option, data binding uses the property's data type as declared in the ActionScript code.

In the following example, data binding will treat x as type DataProvider, even though it is really type Object:

[Bindable(type="DataProvider")]

var x: Object;

 

All properties of all components can participate in data binding. The Bindable tag merely controls which of those properties are available for binding in the Component inspector. If a property is not preceded by the Bindable tag, you can still use it for data binding, but you have to create the bindings using ActionScript.

The Bindable tag is required when you use the ChangeEvent tag. For more information, see About the ChangeEvent tag.
 

About the ChangeEvent tag

TOP

The ChangeEvent tag tells data binding that the component will generate an event any time the value of a specific property changes. In response to the event, data binding executes any binding that has that property as a source. The component only generates the event if you write appropriate ActionScript code in the component. The event should be included in the list of Event metadata declared by the class.

You can declare a property by using var or getter/setter methods. If a property has both a getter and a setter method, you only need to apply the ChangeEvent tag to one.

The ChangeEvent tag has the following syntax:

[Bindable]

[ChangeEvent("event")]

property_declaration or getter/setter function

In the following example, the component generates the change event when the value of the bindable property flavorStr changes:

[Bindable]

[ChangeEvent("change")]

public var flavorStr:String;

When the event that is specified in the metadata occurs, Flash notifies bindings that the property has changed.

You can register multiple events in the tag, as the following example shows:

[ChangeEvent("change1", "change2", "change3")]

Any one of those events indicates a change to the property. They do not all have to occur to indicate a change.

 

About the Collection tag

TOP

Use the Collection tag to describe an array of objects that can be modified as a collection of items in the Values dialog box while authoring. The type of the objects is identified by the collectionItem attribute. A collection property contains a series of collection items that you define in a separate class. This class is either mx.utils.CollectionImpl or a subclass of it. The individual objects are accessed through the methods of the class identified by the collectionClass attribute.



A collection property in the Component inspector and the Values dialog box that appears when you click the magnifying glass.

The syntax for the Collection tag is as follows:

[Collection (name="name", variable="varname", collectionClass="mx.utils.CollectionImpl", collectionItem="coll-item-classname", identifier="string")]

public var varname:mx.utils.Collection;

The following table describes the attributes of the Collection tag:
 

Attribute

Type

Description

name

String

(Required) Name that appears in the Component inspector for the collection.

variable

String

(Required) ActionScript variable that points to the underlying Collection object (for example, you might name a Collection parameter Columns, but the underlying variable attribute might be __columns).

collectionClass

String

(Required) Specifies the class type to be instantiated for the collection property. This is usually mx.utils.CollectionImpl, but it can also be a class that extends mx.utils.CollectionImpl.

collectionItem

String

(Required) Specifies the class of the collection items to be stored within the collection. This class includes its own inspectable properties that are exposed through metadata.

identifier

String

(Required) Specifies the name of an inspectable property within the collection item class that Flash MX uses as the default identifier when the user adds a new collection item through the Values dialog box. Each time a user creates a new collection item, Flash MX sets the item name to identifier plus a unique index (for example, if identifier=name, the Values dialog box displays name0, name1, name2, and so on).

     
     
About the ComponentTask tags

TOP

You can specify one or more Flash JavaScript (JSFL) files to perform tasks for your component from within the Flash authoring environment. Use the ComponentTask tag to define this association between your component and its JSFL file and to associate any additional files required a JSFL file. The JSFL files interact with the JavaScript API in the Macromedia Flash authoring environment.

NOTE : Any JSFL task files and required dependency files declared with the ComponentTask tag must reside in the same folder as your component FLA file when you export your component as a SWC file.

The ComponentTask tag has the following syntax:

[ComponentTask [taskName,taskFile [,otherFile[,]]]

The taskName and taskFile attributes are required. The otherFile attribute is optional

The following example associates SetUp.jsfl and AddNewSymbol.jsfl with the component class named myComponent. The AddNewSymbol.jsfl requires a testXML.xml file and is specified in the otherFile attribute.

[ComponentTask("Do Some Setup","SetUp.jsfl")]

[ComponentTask("Add a new Symbol","AddNewSymbol.jsfl","testXML.xml")]

class myComponent{

//...

}

The following table describes the attributes of the ComponentTask tag:

Attribute

Type

Description

taskName

String

(Required) The name of the task as a string. This name is displayed in the Tasks pop-up menu that appears on the Schema tab of the Component inspector.

taskFile

String

(Required) The name of the JSFL file that implements the tasks within the authoring environment. The file must reside in the same folder as your component FLA when you export your component as a SWC file.

otherFile

String

(Optional) One or more names of files that are required by the JSFL file such as an XML file. The file(s) must reside in the same folder as your component FLA when you export your component as a SWC file.

 

Defining component parameters

TOP

When building a component, you can add parameters that define its appearance and behavior. The most commonly used parameters appear as authoring parameters in the Component inspector and Property inspector. You can also set all inspectable and collection parameters with ActionScript. You define these properties in the component class file by using the Inspectable tag (see About the Inspectable tag).

The following example sets several component parameters in the JellyBean class file, and exposes them with the Inspectable tag in the Component inspector:

class JellyBean{

// a string parameter

[Inspectable(defaultValue="strawberry")]

public var flavorStr:String;

// a string list parameter

[Inspectable(enumeration="sour,sweet,juicy,rotten",defaultValue="sweet")]

public var flavorType:String;

// an array parameter

[Inspectable(name="Flavors", defaultValue="strawberry,grape,orange", verbose=1, category="Fruits")]

var flavorList:Array;

// an object parameter

[Inspectable(defaultValue="belly:flop,jelly:drop")]

public var jellyObject:Object;

// a color parameter

[Inspectable(defaultValue="#ffffff")]

public var jellyColor:Color;

// a setter

[Inspectable(defaultValue="default text")]

function set text(t:String)

}

You can use any of the following types for parameters:

  • Array

  • Object

  • List

  • String

  • Number

  • Boolean

  • Font Name

  • Color

NOTE : The JellyBean class is a theoretical example. To see an actual example, look at the Button.as class file that installs with Flash in the language/First Run/Classes/mx/controls directory.
 

About core functions

TOP

You must define five functions in the component class file: init(), createChildren(), the constructor function, draw(), and size(). When a component extends the UIComponent, these five functions in the class file are called in the following order:

  • init()

    Any initialization occurs during the init() function call. For example, instance member variables can be set at this time and the component bounding box can be hidden.

    After init() is called, the width and height properties are automatically set. See Defining the init() method.

  • createChildren()

    Called as a frame plays in the Timeline. During this time, the component user can call methods and properties to set up the component. Any subobjects the component needs to create are created within the createChildren() function. See Defining the createChildren() method.

  • Constructor function

    Called to create an instance of the component. The component constructor function is generally left empty to avoid initialization conflicts. See About the constructor function.

  • draw()

    Any visual elements of the component that are programmatically created or modified should occur within the draw function. See Defining the draw() method.

  • size()

    This function is called whenever a component is resized at runtime and is passed updated width and height properties of the component. Component subobjects can be sized or moved in relation to the component's updated width and height properties within the size() function. See Defining the size() method.

    These core component functions are described in detail in the sections that follow.
     

Defining the init() method 

TOP

Flash calls the init() method when the class is created. This method is called only once when a component is instantiated.

You should use the init() method to do the following:

  • Call super.init().

    This is required.

  • Make the boundingBox_mc invisible.

    boundingBox_mc.width = 0;

    boundingBox_mc.height = 0;

    boundingBox_mc.visible = false;

  • Create instance member variables.

The width, height, and clip parameters are properly set only after this method is called.

The init() method is called from UIObject's constructor, so the flow of control climbs up the chain of constructors until it reaches UIObject. UIObject's constructor calls the init() method that is defined on lowest subclass. Each implementation of init() should call super.init() so that its base class can finish initializing. If you implement an init() method and you don't call super.init(), the ()init method is not called on any of the base classes, so they might never be in a usable state.

 

Defining the createChildren() method

TOP

Components implement the createChildren() method to create subobjects (such as other components) in the component. Rather than calling the subobject's constructor in the createChildren() method, call createClassObject() or createObject() to instantiate a subobject of your component.

It's a good idea to call size() within the createChildren() method to make sure all children are set to the correct size initially. Also, call invalidate() within the createChildren() method to refresh the screen. (For more information, see About invalidation.)

The createClassObject() method has the following syntax:

createClassObject(className, instanceName, depth, initObject)

The following table describes the parameters:
 

Parameter

Type

Description

className

Object

The name of the class.

instanceName

String

The name of the instance.

depth

Number

The depth for the instance.

initObject

Object

An object that contains initialization properties.


To call createClassObject(), you must know what the children are, because you must specify the name and type of the object, plus any initialization parameters in the call to createClassObject().

The following example calls createClassObject() to create a new Button object for use inside a component:

up_mc.createClassObject(mx.controls.Button, "submit_btn", 1);

You set properties in the call to createClassObject() by adding them as part of the initObject parameter. The following example sets the value of the label property:

form.createClassObject(mx.controls.CheckBox, "cb", 0, {label:"Check this"});

The following example creates TextInput and SimpleButton components:

function createChildren():Void {

if (text_mc == undefined)

createClassObject(TextInput, "text_mc", 0, { preferredWidth: 80, editable:false });

text_mc.addEventListener("change", this);

text_mc.addEventListener("focusOut", this);

if (mode_mc == undefined)

createClassObject(SimpleButton, "mode_mc", 1, { falseUpSkin: modeUpSkinName, falseOverSkin: modeOverSkinName, falseDownSkin: modeDownSkinName });

mode_mc.addEventListener("click", this);

size()

invalidate()

}

 

About the constructor function

TOP

You can recognize a constructor function because it has the same name as the component class. For example, the following code shows the ScrollBar component's constructor function:

function ScrollBar() {

}

In this case, when a new scroll bar is instantiated, the ScrollBar() constructor is called.

Generally, component constructors should be empty. Setting properties in constructors can sometimes lead to overwriting default values, depending on the order of initialization calls.
If your component extends UIComponent or UIObject, Flash automatically calls init(), createChildren(), and size() methods and you can leave your constructor function empty, as shown here:

class MyComponent extends UIComponent{

...

// this is the constructor function

function MyComponent(){

}

}

All version 2 components should define an init() function that is called after the constructor has been called. You should place the initialization code in the component's init() function. For more information, see Defining the init() method.

If your component extends MovieClip, you may want to call an init() method, a createChildren() method, and a method that lays out your component from the constructor function, as shown in the following code example:

class MyComponent extends MovieClip{

...

function MyComponent(){

init()

}

function init():Void{

createChildren();

layout();

}

...

}

 

Defining the draw() method

TOP

You can write code in the draw() method to create or modify visual elements of a component. In other words, in the draw() method, a component draws itself to match its state variables. Since the last draw() method was called, multiple properties or methods may have been called, and you should try to account for all of them in the body of draw().

However, you should not call the draw() method directly. Instead, call the invalidate() method so that calls to draw() can be queued and handled in a batch. This approach increases efficiency and centralizes code. (For more information, see About invalidation.)

Inside the draw() method, you can use calls to the Flash drawing API to draw borders, rules, and other graphical elements. You can also set property values and call methods. You can also call the clear() method, which removes the visible objects.

In the following example from the Dial component (see Building your first component), the draw() method sets the rotation of the needle to the value property:

function draw():Void {

super.draw();

dial.needle._rotation = value;

}

 

Defining the size() method

TOP

When a component is resized at runtime using the componentInstance.setSize() method, the size() function is invoked and passed width and height properties. You can use the size() method in the component's class file to lay out the contents of the component.

At a minimum, the size() method should call the superclass's size() method (super.size()).

In the following example from the Dial component (see Building your first component), the size() method uses the width and height parameters to resize the dial movie clip:

function size():Void {

super.size();

dial._width = width;

dial._height = height;

invalidate();

}

Call the invalidate() method inside the size() method to tag the component for redraw instead of calling the draw() method directly. For more information, see About invalidation.

 

Dispatching events

TOP

If you want your component to broadcast events other than the events it may inherit from a parent class, you must call the dispatchEvent() method in the component's class file.

The dispatchEvent() method is defined in the mx.events.EventDispatcher class and is inherited by all components that extend UIObject. (See EventDispatcher class in Components Language Reference.)

You should also add an Event metadata tag at the top of the class file for each new event. For more information, see About the Event tag.

NOTE : For information about handling component events in a Flash application, see Handling Component Events.

Using the dispatchEvent() method

In the body of your component's ActionScript class file, you broadcast events using the dispatchEvent() method. The dispatchEvent() method has the following syntax:

dispatchEvent(eventObj)

The eventObj parameter is an ActionScript object that describes the event (see the example later in this section).

You must declare the dispatchEvent() method in your code before you call it, as follows:

private var dispatchEvent:Function;

You must also create an event object to pass to dispatchEvent(). The event object contains information about the event that the listener can use to handler the event.

You can explicitly build an event object before dispatching the event, as the following example shows:

var eventObj = new Object();

eventObj.type = "myEvent";

eventObj.target = this;

dispatchEvent(eventObj);

You can also use a shortcut syntax that sets the value of the type property and the target property and dispatches the event in a single line:

ancestorSlide.dispatchEvent({type:"revealChild", target:this});

In the preceding example, setting the target property is optional, because it is implicit.

The description of each event in the Flash 8 documentation lists the event properties that are optional and required. For example, the ScrollBar.scroll event takes a detail property in addition to the type and target properties. For more information, see the event descriptions in Components Language Reference.

Common events

The following table lists the common events that are broadcast by various classes. Every component should broadcast these events if they make sense for that component. This is not a complete list of events for all components, just ones that are likely to be reused by other components. Even though some events specify no parameters, all events have an implicit parameter: a reference to the object broadcasting the event.
 

Event

Use

click

Used by the Button component, or whenever a mouse click has no other meaning.

change

Used by List, ComboBox, and other text-entry components.

scroll

Used by ScrollBar and other controls that cause scrolling (scroll "bumpers" on a scrolling pop-up menu).

 

In addition, because of inheritance from the base classes, all components broadcast the following events:
 

UIComponent event

Description

load

The component is creating or loading its subobjects.

unload

The component is unloading its subobjects.

focusIn

The component now has the input focus. Some HTML-equivalent components (ListBox, ComboBox, Button, Text) might also broadcast focus, but all broadcast DOMFocusIn.

focusOut

The component has lost the input focus.

move

The component has been moved to a new location.

resize

The component has been resized.



The following table describes common key events:
 

Key events

Description

keyDown

A key is pressed. The code property contains the key code and the ascii property contains the ASCII code of the key pressed. Do not check with the low-level Key object, because the event might not have been generated by the Key object.

keyUp

A key is released.

 

About assigning skins

TOP

A user interface (UI) component is composed entirely of attached movie clips. This means that all assets for a UI component can be external to the UI component movie clip, so they can be used by other components. For example, if your component needs check box functionality, you can reuse the existing CheckBox component assets.

The CheckBox component uses a separate movie clip to represent each of its states (FalseUp, FalseDown, Disabled, Selected, and so on). However, you can associate custom movie clips--called skins--with these states. At runtime, the old and new movie clips are exported in the SWF file. The old states simply become invisible to give way to the new movie clips. The ability to change skins during authoring and at runtime is called skinning.

To skin components, create a variable for every skin element (movie clip symbol) used in the component and set it to the symbol's linkage ID. This lets a developer set a different skin element just by changing a parameter in the component, as shown here:

var falseUpIcon = "mySkin";

The following example shows the skin variables for the various states of the CheckBox component:

var falseUpSkin:String = "";

var falseDownSkin:String = "";

var falseOverSkin:String = ""

var falseDisabledSkin:String = "";

var trueUpSkin:String = "";

var trueDownSkin:String = "";

var trueOverSkin:String = "";

var trueDisabledSkin:String = "";

var falseUpIcon:String = "CheckFalseUp";

var falseDownIcon:String = "CheckFalseDown";

var falseOverIcon:String = "CheckFalseOver";

var falseDisabledIcon:String = "CheckFalseDisabled";

var trueUpIcon:String = "CheckTrueUp";

var trueDownIcon:String = "CheckTrueDown";

var trueOverIcon:String = "CheckTrueOver";

var trueDisabledIcon:String = "CheckTrueDisabled";

 

About styles

TOP

You can use styles to register all the graphics in your component with a class and let that class control the color scheme of the graphics at runtime. No special code is necessary in the component implementations to support styles. Styles are implemented entirely in the base classes (UIObject and UIComponent) and skins.

To add a new style to a component, call getStyle("styleName") in the component class. If the style has been set on an instance, on a custom style sheet, or on the global style sheet, the value is retrieved. If not, you may need to install a default value for the style on the global style sheet.

For more information about styles, see Using styles to customize component color and text.

Registering skins to styles

The following example creates a component called Shape. This component displays a shape that is one of two skins: a circle or a square. The skins are registered to the themeColor style.

To register a skin to a style:

  1. Create a new ActionScript file and copy the following code into it:

    import mx.core.UIComponent;

    class Shape extends UIComponent{

    static var symbolName:String = "Shape";

    static var symbolOwner:Object = Shape;

    var className:String = "Shape";

    var themeShape:String = "circle_skin"

    function Shape(){

    }

    function init(Void):Void{

    super.init();

    }

    function createChildren():Void{

    setSkin(1, themeShape);

    super.createChildren();

    }

    }

  2. Save the file as Shape.as.

  3. Create a new Flash document and save it as Shape.fla in the same folder as Shape.as

  4. Draw a circle on the Stage, select it, and press F8 to convert it to a movie clip.

    Give the circle the name and linkage identifier circle_skin.

  5. Open the circle_skin movie clip and place the following ActionScript on Frame 1 to register the symbol with the style name themeColor:

    mx.skins.ColoredSkinElement.setColorStyle(this, "themeColor");

  6. Create a new movie clip for the component.

    Name the movie clip and linkage identifier Shape.

  7. Create two layers. Place a stop() function in the first frame of the first layer. Place the symbol circle_skin in the second frame.

    This is the component movie clip. For more information, see Creating a component movie clip

  8. Open StandardComponents.fla as an external library, and drag the UIComponent movie clip to the Stage on the second frame of the Shape movie clip (with circle_skin).

  9. Close StandardComponents.fla.

  10. Select the Shape movie clip in the library, select Component Definition from the Library context menu (Windows: Right-click, Mac: control-click), and enter the AS 2.0 class name Shape.

  11. Test the movie clip with the Shape component on the Stage.

    To change the theme color, set the style on the instance. The following code changes the color of a Shape component with the instance name shape to red:

    shape.setStyle("themeColor",0xff0000);

  12. Draw a square on the Stage and convert it to a movie clip.

    Enter the linkage name square_skin, and make sure the Export in First Frame check box is selected.

    NOTE : Because the movie clip isn't placed in the component, Export in First Frame must be selected so that the skin is available before initialization.

  13. Open the square_skin movie clip and place the following ActionScript on Frame 1 to register the symbol with the style name themeColor:

    mx.skins.ColoredSkinElement.setColorStyle(this, "themeColor");

  14. Place the following code on the instance of the Shape component on the Stage in the main Timeline:

    onClipEvent(initialize){

    themeShape = "square_skin";

    }

  15. Test the movie clip with Shape on the Stage. The result should display a red square.

Registering a new style name

If you have created a new style name and it is a color style, add the new name to the colorStyles object in the StyleManager.as file (First Run\Classes\mx\styles\StyleManager.as). This

example adds the shapeColor style:

// initialize set of inheriting color styles

static var colorStyles:Object =

{

barColor: true,

trackColor: true,

borderColor: true,

buttonColor: true,

color: true,

dateHeaderColor: true,

dateRollOverColor: true,

disabledColor: true,

fillColor: true,

highlightColor: true,

scrollTrackColor: true,

selectedDateColor: true,

shadowColor: true,

strokeColor: true,

symbolBackgroundColor: true,

symbolBackgroundDisabledColor: true,

symbolBackgroundPressedColor: true,

symbolColor: true,

symbolDisabledColor: true,

themeColor:true,

todayIndicatorColor: true,

shadowCapColor:true,

borderCapColor:true,

focusColor:true,

shapeColor:true

};

Register the new style name to the circle and square skins on Frame 1 of each skin movie clip, as follows:

mx.skins.ColoredSkinElement.setColorStyle(this, "shapeColor");

The color can be changed with the new style name by setting the style on the instance, as shown here:

shape.setStyle("shapeColor",0x00ff00);
 

Incorporating existing components within your component

TOP

In this section, you will build a simple LogIn component that incorporates Label, TextInput and Button components. This tutorial demonstrates how existing components are incorporated in new components by adding their uncompiled Flash (FLA) library symbols. The completed component files, LogIn.fla, LogIn.as and LogIn.swf are located in the examples folder on your hard disk:

The LogIn component provides an interface for entering a name and password. The API for LogIn has two properties, name and password for setting and getting the string values in the name and password TextInput fields. The LogIn component also dispatches a "click" event when the user clicks a button labeled LogIn.

  • Creating the LogIn Flash (FLA) file

  • The LogIn class file

  • Testing and exporting the LogIn component

 

Creating the LogIn Flash (FLA) file

TOP

Start by creating a Flash (FLA) file that will hold our component symbol.

To create the LogIn FLA file:

  1. In Flash, select File > New and create a new document.

  2. Select File > Save As and save the file as LogIn.fla.

  3. Create Select Insert > New Symbol. Name it LogIn, and select the Movie clip type radio button.

    If the Linkage section of the Create New Symbol dialog isn't open, click the Advanced button to reveal it.

  4. Select Export for ActionScript and deselect Export in First Frame.

    Enter a linkage identifier.

  5. The default linkage identifier is LogIn. The rest of these steps assume you use the default value.

    Enter LogIn in the AS 2.0 Class text box. This value is the component class name.

  6. If you put the class in a package, enter the entire package name. For example, mx.controls.CheckBox denotes the CheckBox class in the mx.controls package.

  7. Click OK.

    Flash opens in symbol-editing mode.

  8. Insert a new layer. Name the top layer Actions and the bottom layer Assets.

  9. Select Frame 2 in the Assets layer and insert a keyframe (F6).

    This is the structure of the component movie clip: an Actions layer and an Assets layer. The Actions layer has 1 keyframe and the Assets layer has 2 keyframes.

  10. Select Frame 1 in the Actions layer and open the Actions panel (F9). Enter a stop() global function.

    This prevents the movie clip from proceeding to Frame 2.

  11. Select File > Import > Open External Library and select the StandardComponents.fla file from the Configuration/ComponentFLA folder.

    NOTE : For information about folder locations, see "Configuration folders installed with Flash" in Using Flash.

  12. Select Frame 2 in the Assets layer. From within the StandardComponents.fla library, browse to the Flash UI Components 2 folder. Drag a Button, Label and TextInput component symbol to Frame 2 of the Assets layer.

    Asset dependencies for these components are automatically copied to your LogIn.fla library.

    All the component assets are added to Frame 2 of the Assets layer. Because there is a stop() global function on Frame 1 of the Actions layer, the assets in Frame 2 will not be seen as they are arranged on the Stage.

    You add assets to Frame 2 for two reasons:

    • So that all assets are automatically copied into the library and are available to instantiate dynamically and access their methods, properties, and events.

    • Placing assets in a frame ensures they are loaded more smoothly as the movie is streamed, so you do not need to set the assets in the library to be exported before the first frame. This method prevents an initial data transfer spike that could cause download delays or long pauses.



    Dragging a Button component symbol from the library in StandardComponents.fla to Frame 2 of the Assets layer of LogIn.fla

  13. Close the StandardComponents.fla library.

  14. In the Assets layer, select Frame 1. Drag the BoundingBox movie clip from the LogIn.fla library (inside the Component Assets folder) to the Stage.

  15. Name the BoundingBox instance boundingBox_mc.

  16. Use the Info panel to resize the BoundingBox to the size of the LogInFinal movie clip (340, 150), and position it at 0, 0.

    The BoundingBox instance is used to create the component's live preview and allow the user to handle resize the component during authoring. You must set the size of the bounding box so that it can enclose all the graphical elements in your component.

    NOTE : If you are extending a component (including any version 2 component) you must keep instance names already in use by that component as its code will refer to those instance names. For example, if you include a version 2 component that is already using the instance name boundingBox_mc, do not rename it. For your own components, you can choose any instance name that is unique and that does not conflict with an existing name within the same scope.

  17. Select the LogIn movie clip in the library, and select Component Definition from the Library context menu (Windows: Right-click, Mac: control-click).

  18. In the AS 2.0 Class text box, enter LogIn.

    This value is the name of the ActionScript class. If the class is in a package, the value is the full package. For example, mx.controls.CheckBox denotes the CheckBox class in the mx.controlspackage.

  19. Click OK.

  20. Save the file.

 

The LogIn class file

TOP

The following code is the ActionScript class for the LogIn component. Please read the comments in the code for a description of each section. (For detailed information on the elements of a component class file, see Overview of a component class file).

To create this file, you can create a new ActionScript file in Flash, or use any other text editor. Save the file as LogIn.as in the same folder as the LogIn.fla file.

You can copy or type the following LogIn component ActionScript class code into your new LogIn.as file. Typing rather than copying the code will help you become familiar with each element of the component code.

/* Import the packages so they can be referenced

from this class directly. */

import mx.core.UIComponent;

import mx.controls.Label;

import mx.controls.TextInput;

import mx.controls.Button;

// Event metadata tag

[Event("change")]

[Event("click")]

class LogIn extends UIComponent

{

/* Components must declare these member variables to be proper

components in the components framework. */

static var symbolName:String = "LogIn";

static var symbolOwner:Object = LogIn;

var className:String = "LogIn";]

// The component's graphical representation.

private var name_label:MovieClip;

private var password_label:MovieClip;

private var name_ti:MovieClip;

private var password_ti:MovieClip;

private var login_btn:MovieClip;

private var boundingBox_mc:MovieClip;

private var startDepth:Number = 10;

/* Private member variables available publicly through getter/setters.

These represent the name and password InputText string values. */

private var __name:String;

private var __password:String;

/* Constructor:

While required for all classes, v2 components require

the contstructor to be empty with zero arguments.

All initialization takes place in a required init

method after the class instance has been constructed. */

function LogIn() {

}

/* Initialization code:

The init method is required for v2 components. It must also

in turn call its parent class init() method with super.init().

The init method is required for components extending UIComponent. */

function init():Void {

super.init();

boundingBox_mc._visible = false;

boundingBox_mc._width = 0;

boundingBox_mc._height = 0;

}

/* Create child objects needed at start up:

The createChildren method is required for components

extending UIComponent. */

public function createChildren():Void {

name_label = createObject("Label", "name_label", this.startDepth++);

name_label.text = "Name:";

name_label._width = 200;

name_label._x = 20;

name_label._y = 10;

name_ti = createObject("TextInput", "name_ti", this.startDepth++,{_width:200,_heigh:22,_x:20,_y:30});

name_ti.html = false;

name_ti.text = __name;

name_ti.tabIndex = 1;

/* Set this text input field to have focus.

Note: Make sure to set select Control > Disable Keyboard Shortcuts

in the Flash Debugger if it is not already selected, otherwise

the focus may not set when testing. */

name_ti.setFocus(); ]

name_label = createObject("Label", "password_label", this.startDepth++,{_width:200,_heigh:22,_x:20,_y:60});

name_label.text = "Password:";

password_ti = createObject("TextInput", "password_ti", this.startDepth++,{_width:200,_heigh:22,_x:20,_y:80});

password_ti.html = false;

password_ti.text = __password;

password_ti.password = true;

password_ti.tabIndex = 2;

login_btn = createObject("Button", "login_btn", this.startDepth++,{_width:80,_heigh:22,_x:240,_y:80});

login_btn.label = "LogIn";

login_btn.tabIndex = 3;

login_btn.addEventListener("click", this);

size();

}

/* The draw method is required for v2 components.

It is invoked after the component has been

invalidated by someone calling invalidate().

This batch's up the changes into one redraw, rather

than doing them all individually. This approach leads

to more efficiency and better centralization of code. */

function draw():Void {

super.draw();

}

/* The size method is invoked when the component's size

changes. This is an opportunity to resize the children,

The size method is required for components extending UIComponent. */

function size():Void {

super.size();

// Cause a redraw in case it is needed.

invalidate();

}

/* Event Handler:

Called by the LogIn button when it receives a mouse click.\

Since we want this event to be accessible outside of the scope of

this component, The click event is dispatched using dispatchEvent. */

public function click(evt){

// Update the member variables with the input field contents.

__name = name_ti.text;

__password = password_ti.text;

// Dispatch a click event when the button fires one.

dispatchEvent({type:"click"});

}

/* This is the getter/setter for the name property.

The [Inspectable] metadata makes the property appear

in the Property inspector and allows a default value

to be set. By using a getter/setter you can call invalidate

and force the component to redraw when the value is changed. */

[Bindable]

[ChangeEvent("change")]

[Inspectable(defaultValue="")]

function set name(val:String){

__name = val;

invalidate();

}

function get name():String{

return(__name);

}

[Bindable]

[ChangeEvent("change")]

[Inspectable(defaultValue="")]

function set password(val:String){

__password=val;

invalidate();

}

function get password():String{

return(__password);

}

}

 

Testing and exporting the LogIn component

TOP

You've created the Flash file that contains the graphical elements, the base classes and the class file that contains all the functionality of the LogIn component. Now it's time to test the component.

Ideally, you would test the component as you work, especially while you're writing the class file. The fastest way to test as you work is to convert the component to a compiled clip and use it in the component's FLA file.

When you're completely finished creating a component, export it as a SWC file. For more information, see Exporting and distributing a component.

To test the LogIn component:

  1. In the LogIn.fla file, select the LogIn movie clip in the library and select Convert to Compiled Clip from the Library context menu (Windows: Right-click, Mac: control-click).

    A compiled clip is added to the library with the name LogIn SWF. You are compiling the movie clip to test it, only. Otherwise, you would follow the instructions later in this section to export the LogIn movie clip.

    NOTE : If you've already created a compiled clip (for example, if this is the second or third time you're testing), a Resolve Library Conflict dialog box appears. Select Replace Existing Items to add the new version to the document.

  2. Drag LogIn SWF to the Stage in frame 1 of the main Timeline (make sure you're in the main Timeline, Scene 1, not the movie clip timeline).

    You can set the name and password property in the Parameters tab or the Component Inspector. This is useful if you want default text such as "Enter your name here" to appear before the user has entered anything. When you set its name and/or password property, the default text in the name and password InputText sub-components will change accordingly at runtime.

    To test the value property at runtime, name the LogIn instance on the Stage myLogin and add the following code to Frame 1 in the main Timeline:

    // Creates a text field in which to view the login values.

    createTextField("myLoginValues",10,10,10,340,40)

    myLoginValues.border = true;

    // Event handler for the login component instance's dispatched click event.

    function click(evt){

    /* Here is where authentication would occur.

    For example the name and password would be passed to a web service which authenticates the name and password and returns a session ID and/or permission roles attributed to the user.

    */

    myLoginValues.text = "Processing...\r";

    myLoginValues.text += "Name: " + myLogin.name + " Password: " + myLogin.password;

    }

    myLogin.addEventListener("click",this);

  3. Select Control > Test Movie to test the component in Flash Player.

NOTE : Since you are testing this component within your original document, you may see a warning message about having the same linkage identifier for two symbols. The component will still work. In practice, you will use the new component within another document in which case the linkaged identifier should be unique.

To export the LogIn component:

  1. In the LogIn.fla file, select the LogIn movie clip in the library and select Component Definition from the Library context menu (Windows: Right-click, Mac: control-click).

  2. Check the Display in Components panel.

  3. Click OK.

  4. In the LogIn.fla file, select the LogIn movie clip in the library, again, and select Export SWC File from the Library context menu (Windows: Right-click, Mac: control-click).

  5. Select a location to save the SWC file.

If you save it to the Components folder in the user-level configuration folder, you can reload the Components panel without restarting Flash and the component appears in the Components panel.

NOTE : For information about folder locations, see Configuration folders installed with Flash in Getting Started with Flash.

The completed LogIn component

 

Exporting and distributing a component

TOP

Flash exports components as component packages (SWC files). Components may be distributed as SWC files or as FLA files. (See the article on Macromedia DevNet at www.macromedia.com/support/flash/applications/creating_comps/creating_comps12.html for information about distributing a component as a FLA.)

The best way to distribute a component is to export is as a SWC file, because SWC files contain all the ActionScript, SWF files, and other optional files needed to use the component. SWC files are also useful if you are working at the same time on a component and the application that uses the component.

Whether you're developing a component for someone else's use, or for your own, it's important to test the SWC file as an ongoing part of component development. For example, problems can arise in a component's SWC file that don't appear in the FLA file.

This section describes a SWC file and explains how to import and export SWC files in Flash.

This section contains the following topics:

  • Understanding SWC files

  • Exporting SWC files

  • Importing component SWC files into Flash

 

Understanding SWC files

TOP

A SWC file is a zip-like file (packaged and expanded by means of the PKZIP archive format) generated by the Flash authoring tool.

The following table describes the contents of a SWC file:
 

File

Description

catalog.xml

(Required) Lists the contents of the component package and its individual components, and serves as a directory to the other files in the SWC file.

ActionScript (AS) files

If you create the component with Flash Professional 8, the source code is one or more ActionScript files that contain a class declaration for the component.

The compiler uses the source code for type checking when a component is extended. The AS file is not compiled by the authoring tool because the compiled bytecode is already in the implementing SWF file.

The source code may contain intrinsic class definitions that contain no function bodies and are provided purely for type checking.

SWF files

(Required) SWF files that implement the components. One or more components can be defined in a single SWF file. If the component is created with Flash 8, only one component is exported per SWF file.

Live Preview SWF files

(Optional) If specified, these SWF files are used for live preview in the authoring tool. If omitted, the SWF files that implement the component are used for live preview instead. The Live Preview SWF file can be omitted in nearly all cases; it should be included only if the component's appearance depends on dynamic data (for example, a text field that shows the result of a web service call).

SWD file

(Optional) A SWD file corresponding to the implementing SWF file that allows you to debug the SWF file. The filename is always the same as that of the SWF file, but with the extension.swd.

PNG file

(Optional) A PNG file containing the 18 x 18, 8-bit-per-pixel icon that you use to display a component icon in the authoring tool user interfaces. If no icon is supplied, a default icon is displayed. (See Adding an icon.)

Property inspector SWF file

(Optional) A SWF file that you use as a custom Property inspector in the authoring tool. If you omit this file, the default Property inspector is displayed to the user.

 

You can optionally include other files in the SWC file, after you generate it from the Flash environment. For example, you might want to include a Read Me file, or the FLA file if you want users to have access to the component's source code. To add additional files, use the Macromedia Extension Manager (see www.macromedia.com/exchange/em_download/).

SWC files are expanded into a single directory, therefore each component must have a unique file name to prevent conflicts.
 

Exporting SWC files

TOP

Flash provides the ability to export SWC files by exporting a movie clip as a SWC file. When exporting a SWC file, Flash reports compile-time errors as if you were testing a Flash application.

There are two reasons to export a SWC file:

  • To distribute a finished component

  • To test during development

Exporting a SWC for a completed component

You can export components as SWC files that contain all the ActionScript, SWF files, and other optional files needed to use the component.

To export a SWC file for a completed component:

  1. Select the component movie clip in the Flash library.

  2. Right-click (Windows) or control-click (Mac) to open the Library context menu.

  3. Select Export SWC File from the Library context menu.

  4. Save the SWC file.

Testing a SWC during development

At different stages of development, it's a good idea to export the component as a SWC and test it in an application. If you export the SWC to the Components folder in your user-level

Configuration folder, you can reload the Components panel without quitting and restarting Flash.

To test a SWC during development:

  1. Select the component movie clip in the Flash library.

  2. Right-click (Windows) or control-click (Mac) to open the Library context menu.

  3. Select Export SWC File from the Library context menu.

  4. Browse to the Components folder in your user-level configuration folder.

    Configuration/Components

    NOTE : For information about the location of the folder, see Configuration folders installed with Flash in Getting Started with Flash.

  5. Save the SWC file.

  6. Select Reload from the Components panel's options menu.

    The component appears in the Component panel.

  7. Drag the component from the Component panel into a document.

 

Importing component SWC files into Flash

TOP

When you distribute your components to other developers, you can include the following instructions so that they can install and use them immediately.

To import a SWC file:

  1. Copy the SWC file into the Configuration/Components directory.

  2. Restart Flash.

The component's icon should appear in the Components panel.

 

Final steps in component development

TOP

After you create the component and prepare it for packaging, you can add an icon and a tool tip. To make sure you completed all the necessary steps, you can also refer to the Component development checklist.

This section contains the following topics:

  • Adding an icon

  • Adding a tooltip

  • Component development checklist

Adding an icon

You can add an icon that represents your component in the Components panel of the Flash authoring environment.

To add an icon for your component:

  1. Create a new image.

    The image must measure 18 pixels square, and you must save it in PNG format. It must be 8-bit with alpha transparency, and the upper left pixel must be transparent to support masking.

  2. Add the following definition to your component's ActionScript class file before the class definition:

    [IconFile("component_name.png")]

  3. Add the image to the same directory as the FLA file. When you export the SWC file, Flash includes the image at the root level of the archive.

Adding a tooltip

Tooltips appear when a user rolls the mouse over your component name or icon in the Components panel of the Flash authoring environment.

You define a tooltip in the Component Definition dialog box. You can access this dialog box from the Library options menu (Windows: Right-click, Mac: control-click) of the component's FLA file.

To add a tooltip in the Component Definition dialog box:

  1. With the FLA file of your component open in Flash, make sure the Library is visible (Window > Library menu).

  2. Click the Library options menu (Windows: Right-click, Mac: Control-click).

    The Library options menu is on the right side of the Library title bar, and appears as an icon of three lines and a down triangle.

  3. Select the Component Definition option.

  4. In the Component Definition dialog box, under Options, select Display in the Components Panel.

    The Tool tip text box becomes editable.

  5. Enter the tooltip text for your component in the Tool tip text box.

  6. Click OK to save the changes.

 

Component development checklist

TOP

When you design a component, use the following practices:

  • Keep the file size as small as possible.

  • Make your component as reusable as possible by generalizing functionality.

  • Use the RectBorder class (mx.skins.halo.RectBorder) rather than graphical elements to draw borders around objects. (See RectBorder class in the Components Language Reference.)

  • Use tag-based skinning.

  • Define the symbolName, symbolOwner, and className variables.

  • Assume an initial state. Because style properties are now on the object, you can set initial settings for styles and properties so your initialization code does not have to set them when the object is constructed, unless the user overrides the default state.

  • When defining the symbol, do not select the Export in First Frame option unless absolutely necessary. Flash loads the component just before it is used in your Flash application, so if you select this option, Flash preloads the component in the first frame of its parent. The reason you typically do not preload the component in the first frame is for considerations on the web: the component loads before your preloader begins, defeating the purpose of the preloader.

  • Avoid multiple frame movie clips (except for the two-frame Assets layer).

  • Always implement init() and size() methods and call Super.init() and Super.size() respectively, but otherwise keep them lightweight.

  • Avoid absolute references, such as _root.myVariable.

  • Use createClassObject() instead of attachMovie().

  • Use invalidate() and invalidateStyle() to invoke the draw() method instead of calling draw() explicitly.

  • When incorporating Flash components into your component, use their uncompiled movie symbols located in the library of the StandardComponents.fla file from the Configuration/ComponentFLA folder.

 

Copyright ADOBE - All Rights Reserved Worldwide

 

 

More Topics:

Working with Flash Documents

How to work in Flash WorkSpace

Working with Projects in Flash

Process to Build your First Application in Flash

Using Symbols, Instances and Library Assets in Flash

How to Build Video Player in Flash

How to Work with Color, Strokes and Fills in Flash

How to Create Document in Flash

What is Vector and Bitmap Graphics in Flash

How to Create a Banner in Flash, Part 1

How to Work with Text in Flash

How to Create a Banner in Flash, Part 2

How to Use Imported Artwork in Flash

How to Create a Banner in Flash, Part 3

How to Work with Graphic Objects in Flash

How to Work with Layers in Flash

How to Use Filters and Blends

Working with Graphics in Flash

What is Accessibility Features in Flash

How to Create Motion (Shape Tween & Motion Tween) in Flash

How to Create an Application in Flash

What is Masking in Flash

How to Work with Video in Flash

How to Use Layout Tools in Flash

What are Behaviors in Flash

How to Work with Sound in Flash

How to Create Symbols and Instances in Flash

What is ActionScript in Flash

How to Write ActionScript With Script Assist in Flash

How to Add Button Animation and Navigation in Flash

What is Data Integration in Flash

How to Work with Screens

How to Create a Presentation with Screens

What is Extending Flash

How to Create Multilanguage Text in Flash

How to Create Graphics: Draw in Flash

What is Flash Lite

Ways of Data Integration

How to Create Graphics: Create a Timeline Animation in Flash

Getting Started with Flash Lite in Flash

How to Publish Flash Documents

How to Create Graphics: Making Animations with Easing

Learning Flash Lite 1.X ActionScript in Flash

How to Export Flash Content and Images from Flash

How to Create Graphics: Applying Gradients in Flash

Process of Writing and Editing ActionScript 2.0 in Flash

How to Create Accessible Content in Flash

How to Create Graphics: Apply Graphic Filters and Blends

What is Data and Data Types in Flash

Process of Printing from SWF Files in Flash

Using ActionScript: How to Use Script Assist mode in Flash

Learn Syntax and Language Fundamentals in Flash

How to Create E-learning Content in Flash

Using ActionScript: How to Write Scripts in Flash

Working with Functions and Methods in Flash

Process of Using Templates in Flash

Using ActionScript: Process of Adding Interactivity in Flash

What are Classes in Flash

Control Tag Summary of XML to UI in Flash

Using ActionScript: How to Create a Form with Conditional Logic and Send Data in Flash

What is Inheritance in Flash

What is Data Integration: Overview

Using ActionScript: How to Work with Objects and Classes in Flash

Overview on Interfaces in Flash

What is Data Integration: Using XML for a Timesheet

How to Work with Text and Strings in Flash

How to use Handling Events in Flash

What is Data Integration: Using XUpdate to Update the Timesheet

Learning Animation, Filters and Drawings in Flash

How to Work with Movie Clips in Flash

How to Create Interaction with ActionScript in Flash

How to Work with Images, Sound, and Video in Flash

How to Work with External Data in Flash

What is Security in Flash

How to Debug Applications in Flash

List of Error Messages in Flash

Using Object-Oriented Programming with ActionScript 1.0 in Flash

How to Write Scripts for Earlier Versions of Flash Player in Flash

List of all Keyboard Keys and Key Code Values for using in Flash

Terminology

Introduction to Components in Flash

What are Components in Flash

How to Create an Application with Components

How to Work with Components in Flash

How to Handle Component Events in Flash

How to Customize Components in Flash

How to Create Components in Flash

What is Collection Properties in Flash