Flash As2 Components Help
Flash As2 Components Help
0
™
COMPONENTS
© 2007 Adobe Systems Incorporated. All rights reserved.
If this guide is distributed with software that includes an end user agreement, this guide, as well as the software described in it, is
furnished under license and may be used or copied only in accordance with the terms of such license. Except as permitted by any
such license, no part of this guide may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means,
electronic, mechanical, recording, or otherwise, without the prior written permission of Adobe Systems Incorporated. Please note
that the content in this guide is protected under copyright law even if it is not distributed with software that includes an end user
license agreement.
The content of this guide is furnished for informational use only, is subject to change without notice, and should not be
construed as a commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability
for any errors or inaccuracies that may appear in the informational content contained in this guide.
Please remember that existing artwork or images that you may want to include in your project may be protected under copyright
law. The unauthorized incorporation of such material into your new work could be a violation of the rights of the copyright
owner. Please be sure to obtain any permission required from the copyright owner.
Any references to company names in sample templates are for demonstration purposes only and are not intended to refer to any
actual organization.
Adobe®, Flash®, Flash® Player, Flash® Video, and Macromedia® are either registered trademarks or trademarks of Adobe Systems
Incorporated in the United States and/or other countries.
Macintosh® is a trademark of Apple Computer, Inc., registered in the United States and other countries. Windows® is either a
registered trademark or a trademark of Microsoft Corporation in the United States and/or other countries. All other trademarks
are the property of their respective owners.
Portions of this product contain code licensed from Nellymoser. (www.nellymoser.com).
Sorenson™ Spark™ video compression and decompression technology licensed from
Sorenson Media, Inc.
Flash CS3 video is powered by On2 TrueMotion video technology. © 1992-2005 On2 Technologies, Inc. All Rights Reserved.
http://www.on2.com.
Adobe Systems Incorporated, 345 Park Avenue, San Jose, California 95110, USA. Notice to U.S. Government End Users. The
Software and Documentation are “Commercial Items,” as that term is defined at 48 C.F.R. §2.101, consisting of “Commercial
Computer Software” and “Commercial Computer Software Documentation,” as such terms are used in 48 C.F.R. §12.212 or 48
C.F.R. §227.7202, as applicable. Consistent with 48 C.F.R. §12.212 or 48 C.F.R. §§227.7202-1 through 227.7202-4, as
applicable, the Commercial Computer Software and Commercial Computer Software Documentation are being licensed to U.S.
Government end users (a) only as Commercial Items and (b) with only those rights as are granted to all other end users pursuant
to the terms and conditions herein. Unpublished-rights reserved under the copyright laws of the United States. Adobe Systems
Incorporated, 345 Park Avenue, San Jose, CA 95110-2704, USA. For U.S. Government End Users, Adobe agrees to comply with
all applicable equal opportunity laws including, if appropriate, the provisions of Executive Order 11246, as amended, Section
402 of the Vietnam Era Veterans Readjustment Assistance Act of 1974 (38 USC 4212), and Section 503 of the Rehabilitation
Act of 1973, as amended, and the regulations at 41 CFR Parts 60-1 through 60-60, 60-250, and 60-741. The affirmative action
clause and regulations contained in the preceding sentence shall be incorporated by reference.
Contents
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Intended audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
System requirements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
About the documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Typographical conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Terms used in this manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Additional resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3
Sizing components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Deleting components from Flash documents . . . . . . . . . . . . . . . . . . . . . 55
Using code hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Using ActionScript with screens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
How screens interact with ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Creating custom focus navigation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Managing component depth in a document . . . . . . . . . . . . . . . . . . . . . . 60
Components in Live Preview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Using a preloader with components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
About loading components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Upgrading version 1 components to version 2 architecture . . . . . . . . . 63
4 Contents
Chapter 7: Collection Properties . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Defining a collection property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .182
Simple collection example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .183
Defining the class for a collection item . . . . . . . . . . . . . . . . . . . . . . . . . .185
Accessing collection information programmatically . . . . . . . . . . . . . . .185
Exporting components that have collections to SWC files . . . . . . . . . 187
Using a component that has a collection property . . . . . . . . . . . . . . . . 188
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
Contents 5
6 Contents
Introduction
Flash CS3 Professional is the standard authoring tools for producing high-impact web
experiences. Components are the building blocks for the rich Internet applications that
provide these experiences. A component is a movie clip with parameters that are set during
authoring in Flash, and with ActionScript methods, properties, and events that allow you to
customize the component at runtime. Components are designed to allow developers to reuse
and share code, and to encapsulate complex functionality that designers can use and
customize without using ActionScript.
Components are built on version 2 of the Adobe Component Architecture, which allows you
to easily and quickly build robust applications with a consistent appearance and behavior.
This book describes how to build applications with version 2 components. The related
ActionScript 2.0 Components Language Reference describes each component’s application
programming interface (API). It includes usage scenarios and procedural samples for using the
Flash version 2 components, as well as descriptions of the component APIs, in alphabetical
order.
You can use components created by Adobe, download components created by other
developers, or create your own components.
This chapter contains the following sections:
Intended audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
System requirements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
About the documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Typographical conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Terms used in this manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Additional resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
7
Intended audience
This book is for developers who are building Flash applications and want to use components
to speed development. You should already be familiar with developing applications in Flash
and writing ActionScript.
If you are less experienced with writing ActionScript, you can add components to a
document, set their parameters in the Property inspector or Component inspector, and use
the Behaviors panel to handle their events. For example, you could attach a Go To Web Page
behavior to a Button component that opens a URL in a web browser when the button is
clicked without writing any ActionScript code.
If you are a programmer who wants to create more robust applications, you can create
components dynamically, use ActionScript to set properties and call methods at runtime, and
use the listener event model to handle events.
For more information, see Chapter 3, “Working with Components,” on page 47.
System requirements
Adobe components do not have any system requirements in addition to Flash.
Any SWF file that uses version 2 components must be viewed with Flash Player 6 (6.0.79.0)
or later, and must be published for ActionScript 2.0 (you can set this through File > Publish
Settings, in the Flash tab).
8 Introduction
Typographical conventions
The following typographical conventions are used in this book:
■ Italic font indicates a value that should be replaced (for example, in a folder path).
■ Code font indicates ActionScript code, including method and property names.
■ Code font italic indicates a code item that should be replaced (for example, an
ActionScript parameter).
■ Bold font indicates a value that you enter.
Additional resources
For the latest information on Flash, plus advice from expert users, advanced topics, examples,
tips, and other updates, see the Adobe DevNet website at www.adobe.com/devnet, which is
updated regularly. Check the website often for the latest news on Flash and how to get the
most out of the program.
For TechNotes, documentation updates, and links to additional resources in the Flash
Community, see the Adobe Flash Support Center at www.adobe.com/support/flash.
For detailed information on ActionScript terms, syntax, and usage, see Learning ActionScript
2.0 in Adobe Flash and the ActionScript 2.0 Language Reference.
For an introduction to using components, see the Adobe On Demand Seminar, Using UI
Components at www.adobe.com/events/main.jsp.
Additional resources 9
10 Introduction
CHAPTER 1
About Components 1
Flash CS3 Professional components are movie clips with parameters that allow you to modify
their appearance and behavior. A component can be a simple user interface control, such as a
radio button or a check box, or it can contain content, such as a scroll pane; a component can
also be non-visual, like the FocusManager that allows you to control which object receives
focus in an application.
Components enable you to build complex Flash applications, even if you don’t have an
advanced understanding of ActionScript. Rather than creating custom buttons, combo boxes,
and lists, you can drag these components from the Components panel to add functionality to
your applications. You can also easily customize the look and feel of components to suit your
design needs.
Components are built on version 2 of the Adobe Component Architecture, which allows you
to build robust applications, easily and quickly, with a consistent appearance and behavior.
The version 2 architecture includes classes on which all components are based, styles and skins
mechanisms that allow you to customize component appearance, a broadcaster/listener event
model, depth and focus management, accessibility implementation, and more.
NO T E
When publishing version 2 components, you must set your publish settings to publish for
ActionScript 2.0 (File > Publish Settings, Flash tab). The version 2 components will not
run correctly if published using ActionScript 1.0 or ActionScript 3.0.
Each component has predefined parameters that you can set while authoring in Flash. Each
component also has a unique set of ActionScript methods, properties, and events, also called
an API (application programming interface), that allows you to set parameters and additional
options at runtime.
For a complete list of components included with Flash, see “Installing components”
on page 12. You can also download components built by members of the Flash community at
the Adobe Exchange at www.adobe.com/cfusion/exchange/index.cfm.
11
This chapter contains the following sections:
Installing components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Where component files are stored . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Modifying the component files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Benefits of using components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Component categories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
About version 2 component architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17
Version 2 component features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
About compiled clips and SWC files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Accessibility and components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Installing components
A set of Adobe components is already installed when you start Flash for the first time. You can
view them in the Components panel.
N OT E
To view version 2 components, you must set your publish settings to publish for
ActionScript 2.0 (File > Publish Settings, Flash tab). The version 2 components do not
display with the default publish settings.
12 About Components
■ Menu
■ MenuBar
■ NumericStepper
■ ProgressBar
■ RadioButton
■ RDBMSResolver
■ ScrollPane
■ TextArea
■ TextInput
■ Tree
■ UIScrollBar
■ WebServiceConnector
■ Window
■ XMLConnector
■ XUpdateResolver
Flash also includes the DataBinding class. To access the class, select Window > Common
Libraries > Classes.
Installing components 13
To install components on a Windows-based or a Macintosh computer:
1. Quit Flash.
2. Place the SWC or FLA file containing the component in the following folder on your
hard disk:
■ In Windows: C:\Program Files\Adobe\ Adobe
Flash CS3\language\Configuration\Components
■ On the Macintosh: Macintosh HD/Applications/Adobe Flash CS3/Configuration/
Components (Macintosh)
3. Start Flash.
4. Set your publish settings to publish for ActionScript 2.0.
(Choose File > Publish Settings, Flash Tab and select ActionScript 2.0 from the
ActionScript dropdown menu.)
5. Select Window > Components to view the component in the Components panel if it isn’t
already open.
14 About Components
The files in the First Run directory are copied to your Documents and Settings path when
Flash is first launched. The Documents and Settings paths are:
■ Windows 2000 or Windows XP: C:\Documents and Settings\username\Local
Settings\Application Data\Adobe\Adobe Flash CS3\language\Configuration\Classes\mx
NO TE
In Windows, the Application Data folder is hidden by default. To show hidden folders and
files, select My Computer to open Windows Explorer, select Tools>Folder Options and
then select the View tab. Under the View tab, select the Show hidden files and folders
radio button.
If you want to modify the source ActionScript files, modify the ones in the Documents
and Settings path. If any of your modifications “break” a component, Flash will restore
the original functionality when you close and relaunch Flash by copying the functional file
from the First Run directory. However if you modify the files in the First run directory and
that “breaks” a component, then you may need to reinstall Flash to restore the source
files back to the functional ones.
Component categories
Components included with Flash fall into the following five categories (the locations of their
ActionScript source files roughly correspond to these categories as well and are listed in
parentheses):
■ Data components (mx.data.*)
Data components that allow you to load and manipulate information from data sources;
the WebServiceConnector and XMLConnector components are data components.
NO T E
The source files for the data components aren’t installed with Flash. However, some
of the supporting ActionScript files are installed.
16 About Components
■ Media components (mx.controls.*)
Media components let you play back and control streaming media; MediaController,
MediaPlayback, and MediaDisplay are media components.
■ User interface components (mx.controls.*)
User interface components (often referred to as “UI Components”) allow you to interact
with an application; for example, the RadioButton, CheckBox, and TextInput
components are user interface controls.
■ Managers (mx.managers.*)
Managers are nonvisual components that allow you to manage a feature, such as focus or
depth, in an application; the FocusManager, DepthManager, PopUpManager,
StyleManager, and SystemManager components are manager components.
■ Screens (mx.screens.*)
The screens category includes the ActionScript classes that allow you to control forms and
slides in Flash.
For a complete list of components, see ActionScript 2.0 Components Language Reference.
Flash MX UI components have been updated to work with Flash Player 7 or later. These
updated components are still based on version 1 architecture. You can download them
from the Adobe Flash Exchange at www.adobe.com/go/v1_components.
Version 2 components are included in the Components panel as compiled clip (SWC)
symbols. A compiled clip is a component movie clip whose code has been compiled.
Compiled clips cannot be edited, but you can change their parameters in the Property
inspector and Component inspector, just as you would with any component. For more
information, see “About compiled clips and SWC files” on page 19.
For a FlashPaper file on the class hierarchy, see the Flash Samples page at
www.adobe.com/go/learn_fl_samples
All components also use the same event model, CSS-based styles, and built-in themes and
skinning mechanisms. For more information on styles and skinning, see Chapter 5,
“Customizing Components,” on page 79. For more information on event handling, see
Chapter 3, “Working with Components,” on page 47.
For a detailed explanation of the version 2 component architecture, see Chapter 6, “Creating
Components,” on page 121.
18 About Components
Themes allow you to drag a predesigned appearance from the library onto a set of
components. (See “About themes” on page 105.)
The Halo theme is the default theme that the version 2 components use. (See “About themes”
on page 105.)
Manager classes provide an easy way to handle focus and depth in a application. (See
“Creating custom focus navigation” on page 59 and “Managing component depth in a
document” on page 60.)
The base classes UIObject and UIComponent provide core methods, properties, and events
to components that extend them. (See “UIComponent class” and “UIObject class” in the
ActionScript 2.0 Components Language Reference.)
Packaging as a SWC file allows easy distribution and concealable code. See Chapter 6,
“Creating Components,” on page 121.
Built-in data binding is available through the Component inspector. For more information,
see “Data Integration” in Using Flash.
An easily extendable class hierarchy using ActionScript 2.0 allows you to create unique
namespaces, import classes as needed, and subclass easily to extend components. See Chapter
6, “Creating Components,” on page 121 and the ActionScript 2.0 Language Reference.
N OT E
Flash 8 and later has several features that are not supported by the v2 components,
including 9-slice (sometimes referred to as “scale-9”), advanced anti-aliasing, and
bitmap caching.
20 About Components
CHAPTER 2
21
The application uses the ComboBox, DataGrid, TextArea, and Button components, as well as
others, to create the application interface. The main page of the interface looks like this:
The application uses the ActionScript WebService class to connect dynamically to a web
service to retrieve the list of offenses (problems.xml) that appear in the combo box. It also uses
ActionScript to handle the user’s interactions with the application.
The application uses data components to connect the interface to another data source. It uses
the XMLConnector component to connect to an XML data file (products.xml) for the list of
gifts and it uses the DataSet component to filter the data and present it to the data grid.
The tutorial requires some familiarity with the Flash authoring environment and some
experience with ActionScript. In the authoring environment, you should have some
experience using panels, tools, the timeline, and the library. All the ActionScript needed for
creating the sample application is provided here within the tutorial. To understand the
scripting concepts and create your own applications, however, you will need additional
experience writing ActionScript.
To see a working version of the completed application, see “Viewing the completed
application” on page 46
Keep in mind that the sample application is for demonstration purposes and therefore is not
as complete as a real-world application.
The start_app.fla file contains three layers: a background layer with a black background
image and text titles, a text layer with text labels for sections of the application, and a
labels layer with labels on the first frame (Home) and the tenth frame (Checkout).
2. Select File > Save As. Rename the file and save it to your hard disk.
3. In the Timeline, select the Labels layer and click the Add Layer button to add a new layer
above it. Name the new layer Form. You will place the component instances in this layer.
The ComboBox component symbol is added to the library (Window > Library). When
you drag an instance of a component to the Stage, the compiled clip symbol for the
component is added to the library. As with all symbols in Flash, you can create
additional instances of the component by dragging the library symbol onto
the Stage.
5. Drag an instance of the DataGrid component from the Components panel onto the Stage.
Place it below the Gift Ideas text. Enter products_dg for the instance name. Enter 400
(pixels) for the width and 130 for the height. Enter 76.0 for the x location and 128.0 for
the y location.
6. Drag an instance of the DataSet component from the Components panel onto the side of
the Stage. (The DataSet component does not appear in the application at runtime. The
DataSet icon is simply a placeholder that you work with in the Flash authoring
environment.) Enter products_ds for the instance name.
Drag an instance of the XMLConnector component from the Components panel to the
side of the Stage. (Like the DataSet component, the XMLConnector component does not
appear in the application at runtime.) Enter products_xmlcon for the instance name.
Click the Parameters tab in the Property inspector, and type http://www.flash-mx.com/
mm/firstapp/products.xml for the URL property. Click the value for the direction
property to activate the combo box, click the down-arrow and select receive from the
list.
N OT E
You can also use the Component inspector (Window > Component Inspector) to set
parameters for components. The Parameters tab in the Property inspector and the
Component inspector work in the same way.
The URL specifies an external XML file with data about the products that appear in the
Gift Ideas section of the application. Later in the tutorial you will use data binding to bind
the XMLConnector, DataSet, and DataGrid components together; the DataSet
component filters data from the external XML file, and the DataGrid component will
display it.
7. Drag an instance of the Button component from the Components panel onto the Stage.
Place it in the lower-right corner of the Stage. Enter checkout_button for the instance
name. Click the Parameters tab and enter Checkout for the label property. For the x and
y coordinates, enter 560.3 and 386.0, respectively.
6. With Frame 1 in the Actions layer still selected, add the following code in the Actions panel
to import the classes:
// Import necessary classes.
import mx.services.WebService;
import mx.controls.*;
import mx.containers.*;
import mx.controls.gridclasses.DataGridColumn;
// Import the custom Cart class.
import Cart;
The instance names you specify here must agree with the instance names that you
assigned when you dragged the components to the Stage.
This code sets the theme color (the highlight color on a selected item), font, and font size
for the components, and also sets the easing for the ComboBox—the way that the drop-
down list appears and disappears when you click the ComboBox title bar.
/* If you are unable to connect to the remote web service, display the
error messages in the Output panel. */
myProblems.onFault = function(error:Object) {
trace("error:");
for (var prop in error) {
trace(" "+prop+" -> "+error[prop]);
}
};
TIP
Press Control+S to save your work and then Control+Enter (or select Control > Test
Movie) to test the application. The combo box should be populated with a list of
offenses at this point and you should see the empty data grid that you created for Gift
Ideas, along with the checkout button.
// Define the function that will be used to set the column’s label
// at runtime.
price_dgc.labelFunction = function(item:Object) {
if (item != undefined) {
return "$"+item.price+" "+item.priceQualifier;
}
};
products_dg.addColumn(price_dgc);
Resetting the filtered property (setting it to false and then to true) at the beginning of
the change() function ensures that the function will work properly if the user changes the
What Did You Do? selection repeatedly.
The filterFunc() function checks whether a given item in the array of gifts falls within the
severity the user selected in the combo box. If the gift is within the selected severity range, it is
displayed in the DataGrid instance (which is bound to the DataSet instance).
The last line of code registers the listener to the problems_cb ComboBox instance.
This code uses the init() method of the Cart class to add a DataGrid instance to the Stage,
define the columns, and position the DataGrid instance on the Stage. It also adds a Button
component instance and positions it, and adds an Alert handler for the button. (To see the
code for the Cart class init() method, open the Cart.as file.)
TI P
Press Control+S to save your work and then Control+Enter (or select Control->Test
Movie) to test the application. When you select an offense in the combo box, the data
grid that you created for Gift Ideas should display a subset of gifts to match the
selected offense.
You will later add ActionScript that dynamically creates an instance of this movie clip for each
product. These movie clip instances will be displayed in the Window component, which you
added to the library earlier. The component instances will be populated with elements from
the external XML file.
1. Drag an instance of the Window component from the Components panel to the library.
The Window component symbol is now added to the library. Later in the tutorial, you
will create instances of the Window component using ActionScript.
2. In the Library panel (Window > Library), click the options menu on the right side of the
title bar and select New Symbol.
3. In the Create New Symbol dialog box, enter ProductForm for Name and select Movie Clip
for Type.
4. Click the Advanced button. Under Linkage, select Export for ActionScript, leave Export in
First Frame selected, and click OK. A document window for the new symbol opens in
symbol-editing mode.
For movie clip symbols that are in the library but not on the Stage, you must select Export
for ActionScript so that you can manipulate them using ActionScript. (Exporting in first
frame means that the movie clip is available as soon as the first frame loads.) Later in the
tutorial you will add ActionScript that will generate an instance of the movie clip
dynamically each time a user clicks a product in the Gift Ideas section.
Setting minimum to 1 specifies that the user must select at least one of the products in
order to add the item to the cart.
10. Drag an instance of the Button component from the Components panel onto the Stage.
Place it beside the NumericStepper component. Set the x, y coordinates to 225, 145. Enter
addToCart_button for the instance name. Click the Parameters tab in the Property
inspector. For label, enter Add To Cart.
This code creates a new event listener called dgListener, and creates instances of the Window
component you added to the library earlier. The title for the new window is set to the
product’s name. The content path for the window is set to the ProductForm movie clip. The
size of the window is set to 340 x 210 pixels.
The code also adds a close button to enable the user to close the window after viewing the
information.
The code includes comments explaining its purpose. It’s a good idea to include
comments like these in all the ActionScript code you write, so that you or anyone
else going back to the code later can easily understand what it was for.
First, the code defines a variable to refer to the selected product in the subsequent code.
Using the thisProduct variable means you don’t have to refer to the specified product
using the path this._parent._parent.products_dg.selectedItem.
Next, the code populates the TextArea and Label instances by using the description,
price, and priceQualifier properties of the thisProduct object. These properties
correspond to elements in the products.xml file that you linked to the products_xmlcon
XMLConnector instance at the beginning of the tutorial. Later in the tutorial, you will
bind the XMLConnector, DataSet, and DataGrid component instances together, and the
elements in the XML file will populate the other two component instances.
Finally, the code uses the image property of the thisProduct object instance to load an
image of the product into the Loader component.
3. Next you will add an event listener to add the product to the cart when the user clicks the
Add to Cart button. (You will add ActionScript to the main Timeline in the application
later in the tutorial, to create an instance of the Cart class.) Add the following code:
var cartListener:Object = new Object();
cartListener.click = function(evt:Object) {
var tempObj:Object = new Object();
tempObj.quantity = evt.target._parent.quantity_ns.value;
tempObj.id = thisProduct.id;
tempObj.productObj = thisProduct;
var theCart = evt.target._parent._parent._parent.myCart;
4. Click the Check Syntax button (the blue check mark above the Script pane) to make sure
there are no syntax errors in the code.
You should check syntax frequently as you add code to an application. Any errors found in
the code are listed in the Output panel. (When you check syntax, only the current script is
checked; other scripts that may be in the FLA file are not checked.) For more information,
see “Debugging your scripts” in Using Flash.
5. Click the arrow button at the upper left of the Document window or select View > Edit
Document to exit symbol editing mode and return to the main Timeline.
TI P
Press Control+S to save your work and then Control+Enter (or select Control >Test
Movie) to test your application. When you click a gift selection now, a window should
appear and display an image of the gift, accompanied by a description, the price, and
a numeric stepper that allows you to choose the quantity that you want.
8. Follow the instructions in steps 14-15 of the Billing Information instructions (see “Create
the Billing Information pane” on page 39) to add a rectangle to the bottom of the form.
This code specifies that, when the user clicks the Checkout button, the playhead moves to the
Checkout label in the Timeline.
4. Next you will add the first child to the Accordion component instance, to accept billing
information from the user. Add the following code:
// Define the children for the Accordion component.
var child1 = checkout_acc.createChild("checkout1_mc", "child1_mc",
{label:"1. Billing Information"});
var thisChild1 = child1.checkout1_sp.spContentHolder;
The first line calls the createChild() method of the Accordion component and creates
an instance of the checkout1_mc movie clip symbol (which you created earlier) with the
instance name child1_mc and the label “1. Billing Information”. The second line of code
creates a shortcut to an embedded ScrollPane component instance.
The first two lines of code are similar to the code for creating the Billing Information
child: you create an instance of the checkout2_mc movie clip symbol, with the instance
name child2_mc and the label “2. Shipping Information”. The second line of code creates
a shortcut to an embedded ScrollPane component instance.
Beginning with the third line of code, you add an event listener to the CheckBox instance.
If the user clicks the check box, the shipping information uses the data the user entered in
the Billing Information pane.
6. Next, create a third child for the Accordion instance, for credit card information:
// Define the third Accordion child.
var child3 = checkout_acc.createChild("checkout3_mc", "child3_mc",
{label:"3. Credit Card Information"});
var thisChild3 = child3.checkout3_sp.spContentHolder;
7. Add this code to create ComboBox instances for the credit card month, year, and type, and
populate each with a statically defined array:
/* Set the values in the three ComboBox instances on the Stage:
ccMonth_cb, ccYear_cb and ccType_cb */
thisChild3.ccMonth_cb.labels = ["01", "02", "03", "04", "05", "06",
"07", "08", "09", "10", "11", "12"];
8. Finally, add the following code to add event listeners to the Checkout button and the Back
button. When the user clicks the Checkout button, the listener object copies the form fields
from the Billing, Shipping, and Credit Card Information panes into a LoadVars object that
is sent to the server. (The LoadVars class lets you send all the variables in an object to a
specified URL.) When the user clicks the Back button, the application returns to the main
screen.
/* Create a listener for the checkout_button Button instance.
This listener sends all the form variables to the server when the user
clicks the Checkout button. */
var checkoutListener:Object = new Object();
checkoutListener.click = function(evt:Object){
evt.target.enabled = false;
/* Create two LoadVars object instances, which send variables to
and receive results from the remote server. */
var response_lv:LoadVars = new LoadVars();
var checkout_lv:LoadVars = new LoadVars();
checkout_lv.billingFirstName = thisChild1.billingFirstName_ti.text;
checkout_lv.billingLastName = thisChild1.billingLastName_ti.text;
checkout_lv.billingCountry = thisChild1.billingCountry_ti.text;
checkout_lv.billingProvince = thisChild1.billingProvince_ti.text;
checkout_lv.billingCity = thisChild1.billingCity_ti.text;
checkout_lv.billingPostal = thisChild1.billingPostal_ti.text;
checkout_lv.shippingFirstName = thisChild2.shippingFirstName_ti.text;
checkout_lv.shippingLastName = thisChild2.shippingLastName_ti.text;
checkout_lv.shippingCountry = thisChild2.shippingCountry_ti.text;
checkout_lv.shippingProvince = thisChild2.shippingProvince_ti.text;
checkout_lv.shippingCity = thisChild2.shippingCity_ti.text;
checkout_lv.shippingPostal = thisChild2.shippingPostal_ti.text;
checkout_lv.ccName = thisChild3.ccName_ti.text;
checkout_lv.ccType = thisChild3.ccType_cb.selectedItem;
checkout_lv.ccNumber = thisChild3.ccNumber_ti.text;
checkout_lv.ccMonth = thisChild3.ccMonth_cb.selectedItem;
checkout_lv.ccYear = thisChild3.ccYear_cb.selectedItem;
47
The Components panel
All components in the user-level configuration/Components directory are displayed in the
Components panel. (For more information about this directory, see “Where component files
are stored” on page 14.)
The Menu and Alert components are two exceptions, and cannot be instantiated using
UIObject.createClassObject(). They use the show() method instead.
For more information, see “About importing class files” in Learning ActionScript 2.0 in Adobe
Flash.
You can use ActionScript methods to set additional parameters for dynamically added
components. For more information, see ActionScript 2.0 Components Language Reference.
N OT E
To add a component to a document at runtime, it must be in the library when the SWF
file is compiled. To add a component to the library, drag the component icon from the
Components panel to the library. Furthermore, if you are loading a movie clip containing
a dynamically instantiated (using ActionScript) component into another movie clip, the
parent movie clip must have the component in the library when the SWF file is compiled.
Components are set to Export in First Frame by default (right-click for Windows, or
control-click for Macintosh, and select the Linkage menu option to see the Export in
First Frame setting). If you want to use a preloader for an application containing
components, you need to change the export frame, see “Using a preloader with
components” on page 61 for instructions.
2. Select the frame in the Timeline where you want to add the component.
3. Open the Actions panel if it isn’t already open.
4. Call createClassObject() to create the component instance at runtime.
This method can be called on its own, or from any component instance. The
createClassObject() method takes the following parameters: a component class name,
an instance name for the new instance, a depth, and an optional initialization object that
you can use to set properties at runtime.
Alternatively, you can import the class package, as in the following example:
import mx.controls.CheckBox;
createClassObject(CheckBox, "cb", 5, {label:"Check Me"});
For more information, see Chapter 4, “Handling Component Events,” on page 65 and the
“UIObject.createClassObject()” in ActionScript 2.0 Components Language Reference.
You can add more instances of a component by dragging the component icon from the library
to the Stage.
For more information about compiled clips, see “About compiled clips and SWC files”
on page 19.
4. To enter or view bindings or schemas for a component, click their respective tabs.
Sizing components
Use the Free Transform tool or the setSize() method to resize component instances.
Resizing the Menu component on the Stage with the Free Transform tool
You can call the setSize() method from any component instance (see
“UIObject.setSize()” in ActionScript 2.0 Components Language Reference) to resize it. The
following code resizes the TextArea component to 200 pixels wide and 300 pixels high:
myTextArea.setSize(200, 300);
N OT E
If you use the ActionScript _width and _height properties to adjust the width and height
of a component, the component is resized but the layout of the content in the
component remains the same. This might cause the component to be distorted in
movie playback.
For more information about sizing components, see their individual entries in the ActionScript
2.0 Components Language Reference.
Screens and movie clips interact with ActionScript in similar ways, but with some
important differences. For more information, see “How screens interact with
ActionScript” on page 57.
For more information, see “Screen class”, “Form class”, and “Slide class”, in the ActionScript
2.0 Components Language Reference.
Symbol instances, including movie clips, buttons, and graphics, also have instance
names. For more information, see “Using symbols, instances, and library assets” in
Using Flash.
■ The class name identifies the ActionScript class to which the screen is assigned. By default,
a slide screen is assigned to the mx.screens.Slide class, and a form screen is assigned to
the mx.screens.Form class. To modify the methods and properties that are available for
the screen, assign the screen to a different class. For more information on ActionScript
classes, see “Classes” in Learning ActionScript 2.0 in Adobe Flash.
■ The Property inspector indicates the registration point in the x and y coordinate fields and
in the registration point grid. For more information, see “Setting properties and
parameters for a screen” in Using Flash. You might want to move the registration point for
greater control in manipulating screen content. For example, to create a spinning shape in
the center of a screen, reposition the screen registration point at the center of the screen
and rotate the screen around its registration point.
You can also use the Accessibility panel to assign a tab index value.
The FocusManager class (API) overrides the default Flash Player focus rectangle and draws a
custom focus rectangle with rounded corners.
For more information about creating a focus scheme in a Flash application, see the
FocusManager class in the ActionScript 2.0 Components Language Reference.
You can also manage relative depths using Layers and the Modify > Arrange menu
options within your document. Components adhere to the same rules for runtime depth
management using layers and arrangement as do movie clips.
Components in Live Preview are not functional. To test component functionality, you can use
the Control > Test Movie command.
If you add a component to the Stage using ActionScript, then you need to drag an
instance of the component you want to add onto the pasteboard (the area around the
Stage). This tells Flash that you’re using the component in your application, and that its
not an unused library item. Remember, Flash does not add unused library items to SWF
files.
Components must be exported after the ActionScript classes that they use.
If you’re using a movie clip with a call to loadMovie(), add the following code:
myMovieClip._lockroot = true;
If you don’t set _lockroot to true in the loader movie clip, the loader only has access to its
own library, but not the library in the loaded movie clip.
The _lockroot property is supported by Flash Player 7. For information about this property,
see _lockroot (MovieClip._lockroot property) in the ActionScript 2.0 Language Reference.
65
■ A listener can be a function or an object. If the listener is an object, it must have a callback
function defined on it. The listener handles the event; this means the callback function is
executed when the event occurs.
■ To register a listener to a broadcaster, call the addEventListener() method from the
broadcaster. Use the following syntax:
componentInstance.addEventListener("eventName",
listenerObjectORFunction);
If you want to use a new listener object, you must create the object, define a property with the
same name as the events, and assign the property to a callback function that executes when the
event is broadcast, as follows:
var listenerObject:Object = new Object();
listenerObject.eventName = function(evtObj:Object){
// your code here
};
If you want to use an existing object, use the same syntax as a new listener object, without
creating the new object, as shown here:
existingObject.eventName = function(evtObj:Object){
// your code here
};
TIP
Finally, you call the addEventListener() method from the component instance that
broadcasts the event. The addEventListener() method takes two parameters: a string
indicating the name of the event and a reference to the listener object.
componentInstance.addEventListener("eventName", listenerObject);
Here is the whole code segment, which you can copy and paste. Be sure to replace any code in
italics with actual values; you can use listenerObject and evtObj or any other legal
identifiers, but you must change eventName to the name of the event.
var listenerObject:Object = new Object();
listenerObject.eventName = function(evtObj:Object){
// code placed here executes
// when the event is triggered
};
componentInstance.addEventListener("eventName", listenerObject);
The following code segment uses the this keyword as the listener object:
function eventName(evtObj:Object){
// code placed here executes
// when the event is triggered
}
componentInstance.addEventListener("eventName", this);
function click(evt){
myText.text = evt.target;
}
myButton.addEventListener("click", this);
The target property of the event object, evt, is a reference to the instance broadcasting
the event. This code displays the value of the target property in the TextInput
component.
function handleEvent(evt){
// check if the event was a click
if (evt.type == "click"){
// do something if the event was click
} else if (evt.type == "change"){
// do something else if the event was change
}
};
instance.addEventListener("click", this);
instance2.addEventListener("change", this);
Then you call the addEventListener() method from the component instance that
broadcasts the event. The addEventListener() method takes two parameters: a string
indicating the name of the event and a reference to the function.
componentInstance.addEventListener("eventName", myFunction);
You can call addEventListener() from any component instance; it is included in every UI
component from the EventDispatcher class. For more information, see
“EventDispatcher.addEventListener()” in ActionScript 2.0 Components Language Reference.
For information about the events a component broadcasts, see each component’s entry in the
ActionScript 2.0 Components Language Reference.
The type property of the event object, evt, is a reference to the event name.
7. Select Control > Test Movie; then select an item in the list and scroll the list to see the
results in the Output panel.
C AU T I ON
In a listener function, the keyword this refers to the component instance that calls
addEventListener(), not to the timeline or the class where the function is defined.
However, you can use the Delegate class to delegate the listener function to a
different scope. See “Delegating events” on page 73. To see an example of function
scoping, see the next section.
If you pass addEventListener() an object, the callback function assigned to that object (or
the function defined on that object) is invoked in the scope of the object. This means that the
keyword this, when used inside the callback function, refers to the listener object, as follows:
var lo:Object = new Object();
lo.click = function(evt){
// this refers to the object lo
trace(this);
}
myButton.addEventListener("click", lo);
However, if you pass addEventListener() a function, the function is invoked in the scope of
the component instance that calls addEventListener(). This means that the keyword this,
when used inside the function, refers to the broadcasting component instance. This causes a
problem if you’re defining the function in a class file. You cannot access the properties and
methods of the class file with the expected paths because this doesn’t point to an instance of
the class. To work around this problem, use the Delegate class to delegate a function to the
correct scope. See “Delegating events” on page 73.
The following code illustrates the scoping of a function when passed to addEventListener()
in a class file. To use this code, copy it into an ActionScript (AS) file named Cart.as. Create a
Flash (FLA) file with a Button component, myButton, and a DataGrid component, myGrid.
Select both components on the Stage and press F8 to convert them into a new symbol named
Cart. In the Linkage properties for the Cart symbol, assign it the class Cart.
class Cart extends MovieClip {
var myButton:mx.controls.Button;
var myGrid:mx.controls.DataGrid;
function myHandler(eventObj:Object){
function onLoad():Void{
myButton.addEventListener("click", myHandler);
}
}
Delegating events
You can import the Delegate class into your scripts or classes to delegate events to specific
scopes and functions (see “Delegate class” in the ActionScript 2.0 Components Language
Reference). To import the Delegate class, use the following syntax:
import mx.utils.Delegate;
compInstance.addEventListener("eventName", Delegate.create(scopeObject,
function));
The scopeObject parameter specifies the scope in which the specified function parameter
is called.
There are two common uses for calling Delegate.create():
■ To dispatch the same event to two different functions.
See the next section.
■ To call functions within the scope of the containing class.
When you pass a function as a parameter to addEventListener(), the function is
invoked in the scope of the broadcaster component instance, not the object in which it is
declared. See “Delegating the scope of a function” on page 75.
Delegating events 73
Delegating events to functions
Calling Delegate.create() is useful if you have two components that broadcast events of
the same name. For example, if you have a check box and a button, you would have to use the
switch statement on the information you get from the eventObject.target property in
order to determine which component is broadcasting the click event.
To use the following code, place a check box named myCheckBox_chb and a button named
myButton_btn on the Stage. Select both instances and press F8 to create a new symbol. Click
Advanced if the dialog box is in basic mode, and select Export for ActionScript. Enter Cart in
the AS 2.0 Class text box. In the Property inspector, set the instance name for the new symbol
to anything you want. The symbol is now associated with the Cart class and an instance of the
symbol becomes an instance of this class.
import mx.controls.Button;
import mx.controls.CheckBox;
class Cart {
var myCheckBox_chb:CheckBox;
var myButton_btn:Button;
function onLoad() {
myCheckBox_chb.addEventListener("click", this);
myButton_btn.addEventListener("click", this);
}
function click(eventObj:Object) {
switch(eventObj.target) {
case myButton_btn:
// sends the broadcaster instance name
// and the event type to the Output panel
trace(eventObj.target + ": " + eventObj.type);
break;
case myCheckBox_chb:
trace(eventObj.target + ": " + eventObj.type);
break;
}
}
}
The following code is the same class file (Cart.as) modified to use Delegate:
import mx.utils.Delegate;
import mx.controls.Button;
import mx.controls.CheckBox;
class Cart {
var myCheckBox_chb:CheckBox;
var myButton_btn:Button;
function chb_onClick(eventObj:Object) {
// sends the broadcaster instance name
// and the event type to the Output panel
trace(eventObj.target + ": " + eventObj.type);
// sends the absolute path of the symbol
// that you associated with the Cart class
// in the FLA file to the Output panel
trace(this)
}
function btn_onClick(eventObj:Object) {
trace(eventObj.target + ": " + eventObj.type);
}
}
Because the function is invoked in the scope of the broadcaster instance, the keyword this in
the body of the function points to the broadcaster instance, not to the class that contains the
function. Therefore, you cannot access the properties and methods of the class that contains
the function. Use the Delegate class to delegate the scope of a function to the containing class
so that you can access the properties and methods of the containing class.
The following example uses the same approach as the previous section with a variation of the
Cart.as class file:
import mx.controls.Button;
import mx.controls.CheckBox;
class Cart {
var myCheckBox_chb:CheckBox;
Delegating events 75
var myButton_btn:Button;
function onLoad() {
myCheckBox_chb.addEventListener("click", chb_onClick);
}
function chb_onClick(eventObj:Object) {
// You would expect to be able to access
// the i variable and output 10.
// However, this sends undefined
// to the Output panel because
// the function isn't scoped to
// the Cart instance where i is defined.
trace(i);
}
}
To access the properties and methods of the Cart class, call Delegate.create() as the second
parameter of addEventListener(), as follows:
import mx.utils.Delegate;
import mx.controls.Button;
import mx.controls.CheckBox;
class Cart {
var myCheckBox_chb:CheckBox;
var myButton_btn:Button;
// define a variable to access
// from the chb_onClick function
var i:Number = 10
function onLoad() {
myCheckBox_chb.addEventListener("click", Delegate.create(this,
chb_onClick));
}
function chb_onClick(eventObj:Object) {
// Sends 10 to the Output panel
// because the function is scoped to
// the Cart instance
trace(i);
}
}
Property Description
type A string indicating the name of the event.
target A reference to the component instance broadcasting the event.
When an event has additional properties, they are listed in the event’s entry in the
Components Dictionary.
The event object is automatically generated when an event is triggered and passed to the
listener object’s callback function or the listener function.
You can use the event object inside the function to access the name of the event that was
broadcast, or the instance name of the component that broadcast the event. From the instance
name, you can access other component properties. For example, the following code uses the
target property of the evtObj event object to access the label property of the myButton
instance and sends the value to the Output panel:
var myButton:mx.controls.Button;
var listener:Object;
listener.click = function(evtObj){
trace("The " + evtObj.target.label + " button was clicked");
}
myButton.addEventListener("click", listener);
For example:
on(click){
trace(this);
}
Flash runs the code inside the on() handler when the event for the on() handler occurs
(in this case, a button click).
4. Select Control > Test Movie and click the button to see the output.
Customizing Components 5
You might want to change the appearance of components as you use them in different
applications. You can customize component appearance using the following three approaches,
individually or in combination:
Styles User interface (UI) components have style properties that set the appearance of some
aspects of a component. Each component has its own set of modifiable style properties, and
not all visual aspects of a component can be changed by setting a style. For more information,
see “Using styles to customize component color and text” on page 80.
Skins A skin comprises the collection of symbols that make up the graphical display of a
component. Skinning is the process of changing the appearance of a component by modifying
or replacing its source graphics. A skin can be a small piece, like a border’s edge or corner, or a
composite piece like the entire picture of a button in its up state (the state in which it hasn’t
been pressed). A skin can also be a symbol without a graphic, which contains code that draws
a piece of the component. Some aspects of a component that cannot be set through its style
properties can be set by modifying the skin. For more information, see “About skinning
components” on page 93.
Themes A theme is a collection of both styles and skins that you can save as a FLA file and
apply to another document. For more information, see “About themes” on page 105.
This chapter contains the following sections:
Using styles to customize component color and text . . . . . . . . . . . . . . . . . . . . . . . . . . 80
About skinning components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
About themes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Combining skinning and styles to customize a component . . . . . . . . . . . . . . . . . . . .114
79
Using styles to customize component
color and text
Flash provides style properties that you can edit for every UI component. Within the
documentation for each specific component, you’ll see a table that lists the modifiable styles
for that component (for example, you can see a table of styles for the Accordion component in
“Using styles with the Accordion component” in the ActionScript 2.0 Components Language
Reference). Additionally, UI components inherit the setStyle() and getStyle() methods
from the UIObject class (see “UIObject.setStyle()” and “UIObject.getStyle()” in
ActionScript 2.0 Components Language Reference). For a component instance, you can use the
setStyle() and getStyle() methods to set and get style property values, as shown later in
“Setting styles on a component instance” on page 82.
NO T E
80 Customizing Components
Understanding style settings
As you use styles and style declarations, you’ll notice that you can set styles in various ways (at
the global, theme, class, style declaration, or style property levels). And, some style properties
may be inherited from a parent component (for example, an Accordion child panel may
inherit a font treatment from the Accordion component). Here are a few key points about
style behavior:
Theme dependence The style properties you can set on a particular component are
determined by the current theme. By default, Flash components are designed to use the Halo
theme, but Flash also provides a Sample theme. So, when you read a style properties table, like
the one for the Button component in “Using styles with the Button component” in the
ActionScript 2.0 Components Language Reference, notice which theme supports the style you
want. The table indicates Halo, Sample, or Both (meaning both themes support the style
property). To change the current theme, see “Switching themes” on page 105.
Inheritance You cannot set inheritance within ActionScript. A component child is designed
either to inherit a style from the parent component, or not.
Global style sheets Style declarations in Flash don’t support “cascading” for Flash
documents the way CSS does for HTML documents. All style sheet declaration objects are
defined at the application (global) level.
Precedence If a component style is set in more than one way (for example, if textColor is
set at the global level and at the component instance level), Flash uses the first style it
encounters according to the order listed in “Using global, custom, and class styles in the
same document” on page 89.
Setting styles
The existence of style properties, their organization within style declarations, and the broader
organization of style declarations and graphics into themes enables you to customize a
component in the following ways:
■ Set styles on a component instance.
You can change color and text properties of a single component instance. This is effective
in some situations, but it can be time consuming if you need to set individual properties
on all the components in a document.
For more information, see “Setting styles on a component instance” on page 82.
■ Adjust the global style declaration that sets styles for all components in a document.
If you want to apply a consistent look to an entire document, you can create styles on the
global style declaration.
For more information, see “Setting global styles” on page 84.
For example, the following code sets the accent colors on a Button instance called myButton
that uses the Halo theme:
myButton.setStyle("themeColor", "haloBlue");
N OT E
You can also access the styles directly as properties (for example, myButton.color =
0xFF00FF).
82 Customizing Components
Style properties set on a component instance through setStyle() have the highest priority
and override all other style settings based on style declaration or theme. However, the more
properties you set using setStyle() on a single component instance, the slower the
component will render at runtime. You can speed the rendering of a customized component
with ActionScript that defines the style properties during the creation of the component
instance using “UIObject.createClassObject()”, and placing the style settings in the
initObject parameter. For example, with a ComboBox component in the current document
library, the following code creates a combo box instance named my_cb, and sets the text in
the combo box to italic and aligned right:
createClassObject(mx.controls.ComboBox, "my_cb", 1, {fontStyle:"italic",
textAlign:"right"});
my_cb.addItem({data:1, label:"One"});
NO T E
If you want to change multiple properties, or change properties for multiple component
instances, you can create a custom style. A component instance that uses a custom style
for multiple properties will render faster than a component instance with several
setStyle() calls. For more information, see “Setting custom styles for groups of
components” on page 85.
To set or change a property for a single component instance that uses the Halo
theme:
1. Select the component instance on the Stage.
2. In the Property inspector, give it the instance name myComponent.
3. Open the Actions panel and select Scene 1, then select Layer 1: Frame 1.
4. Enter the following code to change the instance to orange:
myComponent.setStyle("themeColor", "haloOrange");
So, for example, with a Button component in the library, the following ActionScript
creates a button instance my_button at depth 1 with the text styles set to purple
and italicized:
createClassObject(mx.controls.Button, "my_button", 1, {label:"Hello",
color:"0x9900CC", fontStyle:"italic"});
84 Customizing Components
3. In the Actions panel, use code like the following to change properties on the global style
declaration. You need to list only the properties whose values you want to change, as
shown here:
_global.style.setStyle("color", 0xCC6699);
_global.style.setStyle("themeColor", "haloBlue")
_global.style.setStyle("fontSize",16);
_global.style.setStyle("fontFamily" , "_serif");
Custom style settings have priority over class, inherited, and global style settings. For a list of
style precedence, see “Using global, custom, and class styles in the same document”
on page 89.
5. Use the following syntax to create an instance of the CSSStyleDeclaration object to define
the new custom style format:
var new_style:Object = new CSSStyleDeclaration();
6. Give your style declaration a name, like “myStyle,” in the _global.styles list of custom
style declarations, and identify the object containing all the properties for your new style
declaration.
_global.styles.myStyle = new_style;
7. Use the setStyle() method (inherited from the UIObject class) to add properties to the
new_style object, which are in turn associated with the custom style declaration myStyle:
new_style.setStyle("fontFamily", "_serif");
new_style.setStyle("fontSize", 14);
new_style.setStyle("fontWeight", "bold");
new_style.setStyle("textDecoration", "underline");
new_style.setStyle("color", 0x666699);
8. In the same Script pane, use the following syntax to set the styleName property of three
specific components to the custom style declaration name:
a.setStyle("styleName", "myStyle");
b.setStyle("styleName", "myStyle");
c.setStyle("styleName", "myStyle");
You can also access styles on the custom style declaration using the setStyle() and
getStyle() methods through the declaration’s global styleName property. For example, the
following code sets the backgroundColor style on the myStyle style declaration:
_global.styles.myStyle.setStyle("themeColor", "haloOrange");
However, steps 5 and 6 associated the new_style instance with the style declaration so you
can use the shorter syntax, like new_style.setStyle("themeColor", "haloOrange").
For more information about the setStyle() and getStyle() methods, see
“UIObject.setStyle()” and “UIObject.getStyle()” in the ActionScript 2.0 Components
Language Reference.
86 Customizing Components
Setting styles for a component class
You can define a class style declaration for any class of component (Button, CheckBox, and so
on) that sets default styles for each instance of that class. You must create the style declaration
before you create the instances. Some components, such as TextArea and TextInput, have class
style declarations predefined by default because their borderStyle and backgroundColor
properties must be customized.
CAUTION
If you replace a class style sheet, make sure to add any styles that you want from the old
style sheet; otherwise, they will be overwritten.
The following code first checks to see if the current theme already has a style declaration for
CheckBox, and, if not, creates a new one. Then the code uses the setStyle() method to
define a style property for the CheckBox style declaration (in this case, “color” sets the color
for all check box label text to blue):
if (_global.styles.CheckBox == undefined) {
_global.styles.CheckBox = new mx.styles.CSSStyleDeclaration();
}
_global.styles.CheckBox.setStyle("color", 0x0000FF);
For a table of the style properties you can set on the CheckBox component, see “Using styles
with the CheckBox component” in the ActionScript 2.0 Components Language Reference.
Custom style settings have priority over inherited and global style settings. For a list of style
precedence, see “Using global, custom, and class styles in the same document” on page 89.
One major difference between the implementation of styles for Flash components, and
cascading style sheets for HTML pages, is that the CSS inherit value is not supported
for Flash components. Styles are either inherited or not by component design.
Inherited styles take priority over global styles. For a list of style precedence, see “Using global,
custom, and class styles in the same document” on page 89.
The following example demonstrates how inheriting styles can be used with an Accordion
component, which is available with Flash.
88 Customizing Components
input2.text = "Text Input";
button2.label = "Button";
button2.move(0, input2.height + 10);
The above code adds two children to the Accordion component and loads each with a
TextInput and Button control, which this example uses to demonstrate style inheritance.
6. Select Control > Test Movie to see the document before adding style inheritance.
7. Add the following ActionScript to the end of the script in the first frame:
accordion.setStyle("fontStyle", "italic");
white 0xFFFFFF
red 0xFF0000
green 0x00FF00
blue 0x0000FF
magenta 0xFF00FF
yellow 0xFFFF00
cyan 0x00FFFF
haloGreen 0x80FF4D
haloBlue 0x2BF5F5
haloOrange 0xFFC200
N O TE
If the color name is not defined, the component may not draw correctly.
You can use any valid ActionScript identifier to create your own color names (for example,
"WindowText" or "ButtonText"). Use the Style Manager to define new colors, as shown
here:
mx.styles.StyleManager.registerColorName("special_blue", 0x0066ff);
90 Customizing Components
Most components cannot handle an object as a color style property value. However, certain
components can handle color objects that represent gradients or other color combinations.
For more information, see the “Using styles” section of each component’s entry in the
ActionScript 2.0 Components Language Reference.
You can use class style declarations and color names to easily control the colors of text and
symbols on the screen. For example, if you want to provide a display configuration screen that
looks like Microsoft Windows, you would define color names like ButtonText and
WindowText and class style declarations like Button, CheckBox, and Window.
NO T E
Some components provide style properties that are an array of colors, such as
alternatingRowColors. You must set these styles only as an array of numeric RGB
values, not color names.
Elastic Provides an elastic effect that falls outside the transition range at one or
both ends. The amount of elasticity is unaffected by the duration.
None Provides an equal movement from start to end with no effects, slowing,
or speeding. This transition is also commonly referred to as a linear
transition.
Regular Provides for slower movement at one or both ends for a speeding-up
effect, a slowing-down effect, or both.
Strong Provides for much slower movement at one or both ends. This effect is
similar to Regular but is more pronounced.
Each of the classes in the mx.transitions.easing package provides the following three easing
methods:
Because the easing methods are static methods of the easing classes, you never need to
instantiate the easing classes. The methods are used in calls to setStyle(), as in the following
example.
import mx.transitions.easing.*;
trace("_global.styles.Accordion = " + _global.styles.Accordion);
_global.styles.Accordion.setStyle("openDuration", 1500);
_global.styles.Accordion.setStyle("openEasing", Bounce.easeOut);
N O TE
The default equation used by all transitions is not available in the easing classes listed
above. To specify that a component should use the default easing method after another
easing method has been specified, call setStyle("openEasing", null).
For more information see “Applying easing methods to components” in the ActionScript 2.0
Components Language Reference.
92 Customizing Components
Getting style property values
To retrieve a style property value, use “UIObject.getStyle()” in ActionScript 2.0
Components Language Reference. Every component that is a subclass of UIObject (which
includes all version 2 components except the Media components) inherits the getStyle()
method. This means you can call getStyle() from any component instance, just as you can
call setStyle() from any component instance.
The following code gets the value of the themeColor style and assigns it to the variable
oldStyle:
var myCheckBox:mx.controls.CheckBox;
var oldFontSize:Number
oldFontSize = myCheckBox.getStyle("fontSize");
trace(oldFontSize);
94 Customizing Components
Editing component skins in a document
To edit the skins associated with all instances of a particular component in a single document,
copy the skin symbols from the theme to the document and edit the graphics as desired.
The procedure described below is very similar to creating and applying a new theme (see
“About themes” on page 105). The primary difference is that this procedure describes copying
symbols directly from the theme already in use to a single document and editing only a small
number of all skins available. This is appropriate when your modifications are all in a single
document and when you are modifying skins for only a few components. If the edited skins
will be shared in multiple documents or encompass changes in several components, you may
find editing the skins easier if you create a new theme.
An article on advanced skinning can be found online in the Adobe Developer Center at
www.adobe.com/devnet/flash/articles/skinning_2004.html.
The live preview of the components on the Stage will not reflect the edited skins.
96 Customizing Components
9. Select File > Save but don’t close MyTheme.fla. Now you must create a new document in
which to apply the edited skin to a component.
For more information, see “Applying new skins to a component” on page 99, “Applying
new skins to a subcomponent” on page 100, or “Changing skin properties in a
subcomponent” on page 103.
N OT E
Flash does not display changes made to component skins when you view components
on the Stage using Live Preview.
In this example you’re using a color that already corresponds to an existing style name in
the Sample style. Wherever possible, it’s best to use style names corresponding to official
Cascading Style Sheet standards or styles provided by the Halo and Sample themes.
9. Repeat steps 5-8 until you’ve edited all the skins you want to change.
For this example, repeat these steps for the RadioTrueDisabled skin, but instead of
converting the existing graphic to a movie clip, delete the graphic and drag the existing
Inner Circle symbol to the RadioTrueDisabled skin element.
10. When you finish editing the skin symbol, click the Back button at the left side of the edit
bar at the top of the Stage to return to document-editing mode.
11. Drag an instance of the component to the Stage.
For this example, drag two RadioButton components to the Stage, set one to selected, and
use ActionScript to set both to disabled in order to see the changes.
12. Add ActionScript code to the document to set the new style property on the component
instances or at the global level.
For this example, set the property at the global level as follows:
_global.style.setStyle("symbolBackgroundDisabledColor", 0xD9D9D9);
98 Customizing Components
Applying new skins to a component
Once you have created a new skin, you must apply it to a component in a document. You can
use the createClassObject() method to dynamically create the component instances, or
you can manually place the component instances on the Stage. There are two different ways
to apply skins to component instances, depending on how you add the components to
a document.
You can then enter the following code on Frame 1 to create a list dynamically:
createClassObject(List, "myListBox", 0, {dataProvider:
["AL","AR","AZ", "CA","HI","ID", "KA","LA","MA"]});
Or, you can drag a List component from the library to the Stage.
Set enough data so that the scroll bars appear, or set the vScrollPolicy property
to true.
Add enough data so that the vertical scroll bar appears, or set vScrollPolicy to
true.
The following example explains how to skin something that’s already on the Stage. This
example skins only List scroll bars; any TextArea or ScrollPane scroll bars would not
be skinned.
13. Select File > Save and save this file as MyVScrollBar.as.
14. Click a blank area on the Stage and, in the Property inspector, click the Publish
Settings button.
15. Click the ActionScript Version Settings button.
16. Click the Add New Path (+) button to add a new classpath, and select the Target button
to browse to the location of the MyVScrollBar.as file on your hard disk.
17. Select Control > Test Movie.
To skin a subcomponent:
1. Follow the steps in “Editing component skins in a document” on page 95, but edit a scroll
bar skin. For this example, edit the ScrollDownArrowDown skin and give it the new name
MyScrollDownArrowDown.
2. Select File > New and create a Flash document.
3. Select File > Save and give the file a unique name, such as MyComboTest.fla.
4. Drag MyScrollDownArrowDown from the theme library above to the library of
MyComboTest.fla.
This adds the symbol to the library, but doesn’t make it visible on the Stage.
5. Select Insert > New Symbol and give the symbol a unique name, such as MyComboBox.
8. When you finish editing the symbol, click the Back button at the left side of the edit bar at
the top of the Stage to return to document-editing mode.
9. Drag a ComboBox component to the Stage.
10. In the Property inspector, enter as many Label parameters as necessary for the vertical scroll
bar to appear.
11. Select File > Save.
12. Select File > New and create a new ActionScript file.
13. Enter the following code:
import mx.controls.ComboBox
import mx.controls.scrollClasses.ScrollBar
class MyComboBox extends ComboBox{
function getDropdown():Object{
var oldName = ScrollBar.prototype.downArrowDownName;
ScrollBar.prototype.downArrowDownName = "MyScrollDownArrowDown";
var r = super.getDropdown();
ScrollBar.prototype.downArrowDownName = oldName;
return r;
}
}
14. Select File > Save and save this file as MyComboBox.as.
15. Return to the file MyComboTest.fla.
16. Click a blank area on the Stage and, in the Property inspector, click the Publish
Settings button.
17. Click the ActionScript Version Settings button.
18. Click the Add New Path (+) button to add a new classpath, and select the Target button
to browse to the location of the MyComboBox.as file on your hard disk.
19. Select Control > Test Movie.
Switching themes
Flash installs two themes: Halo and Sample. You’ll notice that the component reference
information for each component contains a table of style properties you can set for either (or
both) themes. So, when you read a style properties table, like the one for the Button
component in “Using styles with the Button component” in the ActionScript 2.0 Components
Language Reference, notice which theme supports the style you want. The table indicates Halo,
Sample, or Both (meaning both themes support the style property).
The Halo theme is the default theme for components. So, if you want to use the Sample
theme, you need to switch the current theme from Halo to Sample.
If you’re unsure about which components are in the document, drag the entire Sample
Theme movie clip to the Stage. The skins are automatically assigned to components in
the document.
NO T E
The Live Preview of the components on the Stage will not reflect the new theme.
4. If you drag individual component Assets folders to the Library panel of your document,
make sure the Assets symbol for each component is set to Export in First Frame.
For example, the Assets folder for the RadioButton component is called RadioButton
Assets. Open the RadioButtonAssets folder, and you’ll see a movie clip symbol called
RadioButtonAssets. The RadioButtonAssets symbol contains all of the individual asset
symbols within it.
5. Select Control > Test Movie to see the document with the new theme applied.
The Live Preview of the components on the Stage will not reflect the new theme.
4. If you dragged individual component Assets folders to the ThemeApply.fla library, make
sure the Assets symbol for each component is set to Export in First Frame.
For example, the Assets folder for the RadioButton component is called RadioButton
Assets; it has a symbol called RadioButtonAssets, which contains all of the individual asset
symbols. If you set Export in First Frame on the RadioButtonAssets symbol, all individual
asset symbols will also export in the first frame.
5. Select Control > Test Movie to see the new theme applied.
4. Select Control > Test Movie to see the combo box with the default style and skinning from
the Halo theme.
2. On the next line, name the new style declaration and add it to the global style definitions:
var new_style:Object = new CSSStyleDeclaration();
_global.styles.myStyle = new_style;
The ActionScript code attached to the first frame of the main Timeline should be as follows:
import mx.styles.CSSStyleDeclaration;
new_style.setStyle("textAlign", "right");
new_style.setStyle("selectionColor", "white");
new_style.setStyle("useRollOver", false);
// borderStyle from RectBorder class
new_style.setStyle("borderStyle", "none");
my_cb.addItem({data:1, label:"One"});
my_cb.addItem({data:2, label:"Two"});
my_cb.setStyle("styleName", "myStyle");
It is possible, but not recommended, to edit the source class files for a component so it
uses symbols with different names as skins, and you can programmatically alter the
ActionScript within a skin symbol (for an example of customized ActionScript and skin
symbols, see “Customizing the Accordion component” in the ActionScript 2.0
Components Language Reference). However, because several components, including
the ComboBox component, share assets with other components, editing the source files
or changing the skin symbol names can have unexpected results.
Make sure you have the symbol SymDownArrow selected, so you are deleting only
the shape inside the movie clip and not the movie clip symbol, itself.
4. Delete the selected down arrow (the black triangle shape, not the whole movie clip) on the
Stage.
6. Select Control > Test Movie to see the skinned combo box:
Creating Components 6
This chapter describes how to create your own component and package it for distribution.
This chapter contains the following sections:
Component source files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .121
Overview of component structure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Building your first component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Selecting a parent class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .131
Creating a component movie clip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Creating the ActionScript class file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Incorporating existing components within your component . . . . . . . . . . . . . . . . . . . 166
Exporting and distributing a component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
Final steps in component development. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
121
■ ActionScript class files
■ In Windows: C:\Program Files\Adobe\Adobe Flash CS3\language\First
Run\Classes\mx
■ On the Macintosh: HD/Applications/Adobe Flash CS3/First Run/Classes/mx
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.
For information about folder locations, see “Configuration folders installed with
Flash” in Using 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.
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.
For a sample of the DialAssets.fla file, see the Flash Samples page at www.adobe.com/go/
learn_fl_samples.
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.
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.
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” on page 140.
// Import the package so you can reference
// the class directly.
import mx.core.UIComponent;
// 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();
function twoDigits(x:Number):Number
{
return (Math.round(x * 100) / 100);
}
function mouseMoveHandler()
{
// Calculate the angle
if (dragging) {
var x:Number = _xmouse - width/2;
var y:Number = _ymouse - height/2;
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.
5. Select Control > Test Movie to test the component in Flash Player.
For information about folder locations, see “Configuration folders installed with
Flash” in Using Flash.
For a sample of a FlashPaper version of the arch_diagram.swf file, see the Flash Samples page
at www.adobe.com/go/learn_fl_samples.
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” on page 179.
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.
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:
boundingBox_mc
// Import packages.
import mx.core.UIObject;
function size(){
// Write code to handle sizing.
super.size();
invalidate();
}
function draw(){
// Write code to handle visual representation.
super.draw();
}
Importing classes
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;
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.
Defining variables
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 Adobe 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";
[Inspectable(defaultValue="strawberry")]
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” on page 158.
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 about getter/setter methods, see “About getter and setter methods” in
Learning ActionScript 2.0 in Adobe Flash.
In the Property inspector and the Parameters tab of the Component inspector, Flash displays
all of these parameters as type String.
Metadata tags
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” on page 146.
Event Defines a component event. See “About the Event tag” on page 148.
ChangeEvent Identifies a event that cause data binding to occur. See “About the
ChangeEvent tag” on page 150.
The following sections describe the component metadata tags in more detail.
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 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:
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.
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;
...
}
To broadcast a particular instance, call the dispatchEvent() method. See “Using the
dispatchEvent() method” on page 160.
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 information on creating data binding in the Flash authoring environment, see “Data
binding” in Using Flash.
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.
A collection property in the Component inspector and the Values dialog box that appears when you
click the magnifying glass.
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 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{
//...
}
[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) {
}
}
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.
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"});
if (mode_mc == undefined)
createClassObject(SimpleButton, "mode_mc", 1, { falseUpSkin:
modeUpSkinName, falseOverSkin: modeOverSkinName, falseDownSkin:
modeDownSkinName });
mode_mc.addEventListener("click", this);
size()
invalidate()
}
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 the next section.
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();
}
...
}
For more information about constructors, see “Writing the constructor function” in Learning
ActionScript 2.0 in Adobe Flash.
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”
on page 123), 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 the next section.
About invalidation
Adobe recommends that a component not update itself immediately in most cases, but that it
instead should save a copy of the new property value, set a flag indicating what is changed,
and call the invalidate() method. (This method indicates that just the visuals for the object
have changed, but size and position of subobjects have not changed. This method calls the
draw() method.)
Dispatching events
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
ActionScript 2.0 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” on page 148.
NO TE
For information about handling component events in a Flash application, see Chapter 4,
“Handling Component Events,” on page 65.
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.
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 Description
event
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.
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";
About styles
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”
on page 80.
function Shape(){
}
function init(Void):Void{
super.init();
}
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.
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.
The color can be changed with the new style name by setting the style on the instance, as
shown here:
shape.setStyle("shapeColor",0x00ff00);
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.
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.controls package.
19. Click OK.
20.Save the file.
/* 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;
}
size();
[Bindable]
[ChangeEvent("change")]
[Inspectable(defaultValue="")]
function set password(val:String){
__password=val;
invalidate();
}
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;
}
3. Select Control > Test Movie to test the component in Flash Player.
NO T E
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.
For information about folder locations, see “Configuration folders installed with
Flash” in Using Flash.
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 If you create the component with Flash, the source code is one or more
(AS) files 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 and later, only one component is exported per SWF file.
Live Preview (Optional) If specified, these SWF files are used for live preview in the
SWF files 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.
Property (Optional) A SWF file that you use as a custom Property inspector in the
inspector authoring tool. If you omit this file, the default Property inspector is displayed
SWF file 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
Adobe Extension Manager (see www.adobe.com/exchange/em_download/).
SWC files are expanded into a single directory, therefore each component must have a unique
file name to prevent conflicts.
For information about the location of the folder, see “Configuration folders installed
with Flash” in Using Flash.
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.
Collection Properties 7
When you create a new custom component in Flash, you can make property values available
for editing by the user. These properties are called collection properties. The property values can
be edited by the user in the Values dialog box (opened from a text box within the Parameters
tab for your component).
Components usually include functionality for a specific task, while remaining flexible for a
range of requirements by the component user. For a component to be flexible, the properties
within the component need to be flexible (in other words, for some components, the
properties can be changed by the component user, as well as by the property values).
Collection properties enable you to create an indeterminate number of editable properties in
an object model. Flash provides a Collection class to help you manage those properties
through the Component inspector.
Specifically, the Collection class is a helper class used to manage a group of related objects,
each called a collection item. If you define a property of your component as a collection item
and make it available to users through the Component inspector, they can add, delete, and
modify collection items in the Values dialog box while authoring.
181
■ Define a collection property using the Collection metadata tag in a component’s
ActionScript file. For more information, see “About the Collection tag” on page 151.
■ Define a collection item as a class in a separate ActionScript file that contains its own
inspectable properties.
In Flash, Collections make it easier for you to manage groups of related items
programmatically. (In previous versions of Flash, component authors managed groups of
related items through multiple programmatically synchronized arrays).
In addition to the Values dialog box, Flash provides the Collection and Iterator interfaces to
manage Collection instances and values programmatically. See “Collection interface” and
“Iterator interface” in ActionScript 2.0 Components Language Reference.
This chapter contains the following sections:
Defining a collection property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Simple collection example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
Defining the class for a collection item . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Accessing collection information programmatically . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Exporting components that have collections to SWC files . . . . . . . . . . . . . . . . . . . . 187
Using a component that has a collection property . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
This section assumes that you know how to create components and inspectable
component properties.
Because UtilsClasses is associated with the FLA file, not the ActionScript class,
Flash throws compiler errors when you check syntax while viewing the component’s
ActionScript class.
You should have already created the CompactDisc class; otherwise, you’ll get
compiler errors when converting to a compiled clip.
To view the CompactDisc.as class file, see “Simple collection example” on page 183.
■ Access the Iterator interface for the collection items by calling the
Collection.getIterator() method, as shown in this example:
var itr:mx.utils.Iterator = __linkButtons.getIterator();
■ Use the Iterator interface to step through the items in the collection. The
Iterator.next() method returns an Object, so you must define the type of your
collection item, as shown in this example:
while (itr.hasNext()) {
var button:ButtonC = ButtonC(itr.next());
...
}
■ Access collection item properties, as appropriate for your application, as shown in this
example:
item.label = button.ButtonLabel;
if (button.ButtonLink != undefined) {
item.data = button.ButtonLink;
}
else {
item.enabled = false;
}
For more information on SWC files, see “Understanding SWC files” on page 175.
189
available in Flash MX editions 12 createClassObject() method 156
categories, described 16 CSSStyleDeclaration 84, 85
class file example 139 customizing
class overview 140 text 80
className variable 142 customizing color and text, using style sheets 80
common events 161
creating movie clips 134
creating subobjects 156 D
defining draw() method 158 data binding, with XML file (tutorial) 28
defining init() method 156 data grids. See DataGrid component
defining parameters 154 data types, setting for instances (tutorial) 26
defining size() method 159 DataGrid component
defining variables 143 adding columns (tutorial) 30
deleting 55 binding to DataSet (tutorial) 28
development checklist 179 DataSet component, binding to XMLConnector and
dispatching events 160 DataGrid (tutorial) 28
editing movie clips 135 defaultPushButton property 60
events 65 Delegate class (tutorial) 73
example of building a component 123, 166 deleting components 55
example of class file with collection 183 DepthManager class, overview 60
exporting and distributing 174 Dial component 123, 166
exporting component as SWC 176 dispatcher (event broadcaster) 65
exporting SWC files 176 dispatching events 160
extending classes 133 documentation
Flash Player support 17 guide to terminology 9
getter/setter methods 143 overview 8
importing SWC files 177 draw() method, defining 158
inheritance 18
installing 12
invalidation, about 159 E
loading 63 event listeners. See listeners
metadata tags 144 Event metadata tag 148
metadata, ComponentTask tag 153 events
preloading 61 about 65
previewing 61 common 161
registering skins to styles 163 delegating scope 73
selecting a parent class 131 dispatching 160
selecting symbol names 142 event object 77
source files 121 handler functions 65
structure of 122 metadata 148
styles 163 See also individual component names
symbolOwner variable 142 exporting components 174
testing SWC files 177 extending classes 133
using in an application (tutorial) 21
See also individual component names
Components panel 48
ComponentTask tag
JavaScript (JSFL) 153
190 Index
F Live Preview feature 61
loading, components 63
Flash JavaScript (JSFL), ComponentTask tag 153
Flash MX editions and available components 12
Flash Player M
and components 17
metadata
support 63
about 144
FocusManager class, creating focus navigation for 59
Collection tag 151
ComponentTask tag 153
G Event tag 148
Inspectable tag 146
getter/setter methods 143 tags, list of 145
global style declarations 84 movie clips
grids. See DataGrid component creating 134
defining as component 137
MovieClip class, extending 134
H
Halo theme 105
handleEvent callback function 69 O
handler functions 65 on() event handler 77
I P
icon, for a component 178 packages 18
import statement 141 parameters. See component parameters
inheritance, in version 2 components 18 parent class, selecting 131
init() method, defining 156 preloading components 61
inspectable parameters 146 previewing components 61
installing components 12 Property inspector 52
instances prototype 103
setting styles on 82
style declarations 80
invalidate() method 159 R
resources, additional Macromedia 9
L
Label component S
tutorial 39
Sample theme 105
library
screen readers, accessibility 20
compiled clips in 52
screens
Library panel 52
instance names 57
StandardComponents 135
interact with ActionScript 57
linkage identifiers for skins 94
registration points 57
listeners
Using ActionScript 56
about 65
using components 58
functions 70
ScrollPane component
objects 66
tutorial 39
scope 72
size() method, defining 159
using with component instances (tutorial) 35
skin properties
using with components (tutorial) 31
Index 191
changing in the prototype 103 T
setting 94
skinning components 93 tabbing 59
skins tags. See metadata
applying to components 99 terminology in documentation 9
applying to subcomponents 100 testing SWC files 177
creating variables for 162 text, customizing 80
editing 96 TextInput component (tutorial) 39
linkage identifiers 94 The Flash file, ActionScript file and SWC file icons
See also individual component names 122
StandardComponents library 135 themes
style declarations about 105
custom 85 applying 110
default class 87 creating 107
global 84 tip text, adding 178
setting class 87 typographical conventions 9
style properties, color 90
style sheets
class 80
U
custom 80 UIComponent class
styles and component inheritance 18
about 80 overview 133
creating components 163 UIObject class
determining precedence 89 about 132
setting 80 upgrading version 1 components 63
setting custom 85
setting global 84
setting on instance 82 V
using (tutorial) 27 Values dialog box 181
See also individual component names variables, defining 143
subclasses, using to replace skins 103 version 1 components, upgrading 63
subcomponents, applying skins 100 version 2 components
subobjects, creating 156 and Flash Player 17
superclass keyword 142 benefits 16
SWC files inheritance 18
about 19
and compiled clips 19
exporting 176 W
exporting collection properties 187 web service, connecting to (tutorial) 27
file format 175 WebService class (tutorial) 27
importing 177 wizard 153
testing 177
symbolName variable 142
symbolOwner variable 142 X
system requirements for components 8 XMLConnector component
binding to DataSet component (tutorial) 28
loading an external XML file (tutorial) 31
specifying schema (tutorial) 29
192 Index