Using Components
Trademarks 1 Step RoboPDF, ActiveEdit, ActiveTest, Authorware, Blue Sky Software, Blue Sky, Breeze, Breezo, Captivate, Central, ColdFusion, Contribute, Database Explorer, Director, Dreamweaver, Fireworks, Flash, FlashCast, FlashHelp, Flash Lite, FlashPaper, Flash Video Encoder, Flex, Flex Builder, Fontographer, FreeHand, Generator, HomeSite, JRun, MacRecorder, Macromedia, MXML, RoboEngine, RoboHelp, RoboInfo, RoboPDF, Roundtrip, Roundtrip HTML, Shockwave, SoundEdit, Studio MX, UltraDev, and WebHelp are eith
Contents Intended audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 System requirements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 About the documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Typographical conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Terms used in this manual . . . . . . . . . . . . . . . . . . . . . . .
Chapter 3: Working with Components. . . . . . . . . . . . . . . . . . . . . .49 The Components panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 Adding components to Flash documents . . . . . . . . . . . . . . . . . . . . . . . . 50 Components in the Library panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 Setting component parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Sizing components . . . . . . . . . . . . .
Chapter 7: Collection Properties . . . . . . . . . . . . . . . . . . . . . . . . . . 187 Defining a collection property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 Simple collection example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .189 Defining the class for a collection item . . . . . . . . . . . . . . . . . . . . . . . . . . 191 Accessing collection information programmatically . . . . . . . . . . . . . . .
Contents
Introduction Macromedia Flash Basic 8 and Macromedia Flash Professional 8 are 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 Macromedia Flash, and with ActionScript methods, properties, and events that allow you to customize the component at runtime.
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.
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 ■ Code font italic ■ Bold font indicates a value that you enter. indicates ActionScript code, including method and property names. indicates a code item that should be replaced (for example, an ActionScript parameter).
Introduction
1 CHAPTER 1 About Components Macromedia Flash 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.
This chapter contains the following sections: Installing components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Where component files are stored . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Modifying the component files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Benefits of using components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Flash Professional 8 includes the Flash Basic 8 components plus the following additional components and classes: ■ Accordion component (Flash Professional only) ■ Alert component (Flash Professional only) ■ Data binding classes (Flash Professional only) ■ DateField component (Flash Professional only) ■ DataGrid component (Flash Professional only) ■ DataHolder component (Flash Professional only) ■ DataSet component (Flash Professional only) ■ DateChooser component (Flash Professional only) ■
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\Macromedia\ Flash 8\language\Configuration\Components On the Macintosh: Macintosh HD/Applications/Macromedia Flash 8/Configuration/ Components (Macintosh) 3. Start Flash. 4. Select Window > Components to view the component in the Components panel if it isn’t already open.
Modifying the component files The source ActionScript files for components are located in: ■ Windows 2000 or Windows XP: C:\Program Files\Macromedia\Flash 8\language\ First Run\Classes\mx ■ Mac OS X: Macintosh HD/Applications/Macromedia Flash 8/First Run/Classes/mx The files in the First Run directory are copied to your Documents and Settings path when Flash is first lunched.
Benefits of using components Components enable you to separate the process of designing your application from the process of coding. They also let you to reuse code, either in components that you create, or by downloading and installing components created by other developers. Components allow coders to create functionality that designers can use in applications.
■ 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.
Version 2 components are written in ActionScript 2.0. Each component is a class and each class is in an ActionScript package. For example, a radio button component is an instance of the RadioButton class whose package name is mx.controls. For more information about packages, see “About packages” in Learning ActionScript 2.0 in Flash.
Themes allow you to drag a predesigned appearance from the library onto a set of components. (See “About themes” on page 108.) The Halo theme is the default theme that the version 2 components use. (See “About themes” on page 108.) Manager classes provide an easy way to handle focus and depth in a application. (See “Creating custom focus navigation” on page 58 and “Managing component depth in a document” on page 59.
When you place a SWC file in the First Run/Components folder, the component appears in the Components panel. When you add a component to the Stage from the Components panel, a compiled clip symbol is added to the library. To compile a movie clip: ■ Right-click (Windows) or Control-click (Macintosh) the movie clip in the Library panel, and then select Convert to Compiled Clip.
CHAPTER 2 2 Creating an Application with Components (Flash Professional Only) Components are prebuilt Flash elements that you can use when creating Macromedia Flash applications. Components include user interface controls, data access and connectivity mechanisms, and media-related elements. Components save you work when building a Flash application by providing you with elements and behavior that you would need to create from scratch otherwise.
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.
Build the main page Follow these steps to create the application’s main page by adding components to a skeletal starter page. Then add ActionScript code to customize the components, import the ActionScript classes that allow you to manipulate the application’s components, and access a web service to populate the combo box with a list of offenses. The code populates the combo box by setting its dataProvider property to receive the results from the web service. 1. Open the first_app_start.
4. Make sure the Form layer is selected. In the Components panel (Window > Components), locate the ComboBox component in the User Interface tree. Drag an instance of ComboBox onto the Stage. Place it below the What Did You Do? text. In the Property inspector (Window > Properties > Properties), enter problems_cb for the instance name. Enter 400 (pixels) for the width. Enter 76.0 for the x location and 82.0 for the y location. NO T E The ComboBox component symbol is added to the library (Window > Library).
Import the component classes Each component is associated with an ActionScript class file that defines its methods and properties. In this section of the tutorial, you will add ActionScript code to import the classes associated with the application’s components. For some of these components, you have already added instances to the Stage. For others, you will add ActionScript later in the tutorial to create instances dynamically.
To import these classes, you will create an Actions layer and add the ActionScript code to the first frame of the main timeline. All the code that you will add to the application in the remaining steps of the tutorial should be placed in the Actions layer. 1. To import the WebServiceClasses item from the Classes library, select Window > Common Libraries > Classes. 2. Drag the WebServiceClasses item from the Classes library into the library for the application.
Set the data types of component instances Next you will assign data types to each of the component instances you dragged to the Stage earlier in the tutorial. ActionScript 2.0 uses strict data typing, which means that you assign the data type when you create a variable. Strict data typing makes code hints available for the variable in the Actions panel. ■ In the Actions panel, add the following code to assign data types to the four component instances that you already created.
Display offenses in the combo box In this section you will add code to connect to a web service that contains the list of offenses (Forgot to Water Your Plants, and so on). The web service description language (WSDL) file is located at www.flash-mx.com/mm/firstapp/problems.cfc?WSDL. To see how the WSDL is structured, browse to the WSDL location. The ActionScript code passes the web service results to the ComboBox instance for display. A function sorts the offenses in order of severity.
Bind data components to display gift ideas In the beginning of the tutorial, you added instances of the DataGrid, DataSet, and XMLConnector components to the Stage. You set the URL property for the XMLConnector instance, named products_xmlcon, to the location of an XML file containing product information for the Gift Ideas section of the application.
Filter the gift ideas to match the offense You will use the Binding tab in the Component inspector to bind the XMLConnector, DataSet, and DataGrid component instances to one another. For information on working with data binding, see “Data Integration (Flash Professional Only)” in Using Flash. 1. With the products_xmlcon (XMLConnector) instance selected on the Stage, click the Bindings tab in the Component inspector. 2. Click the Add Binding button. 3. In the Add Binding dialog box, select the results.
13. In the Value column for the Bound To item, click the magnifying glass icon to open the Bound To dialog box. 14. In the Bound To dialog box, select the products_dg (DataGrid) instance in the Component Path pane. Select dataProvider:array in the Schema Location pane. Click OK. Add columns to the Gift Ideas section Now you are ready to add columns to the data grid in the Gift Ideas section of the application, for displaying product information and price. ■ Select the Actions layer.
Add an event listener to filter the gift ideas In this section, you add an event listener to detect when a user selects an offense in the What Did You Do? section (the problems_cb ComboBox instance). The listener includes a function that filters the Gift Ideas list according to the offense the user chooses. Selecting a minor offense displays a list of modest gifts (such as a CD or flowers); selecting a more serious offense displays more opulent gifts.
Add the cart The next code that you will add creates an instance of the custom Cart class and initializes it. ■ In the Actions panel, add the following code: var myCart:Cart = new Cart(this); myCart.init(); 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.
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 User Interface tree in the Components panel to the library. The Window component symbol is now added to the library.
7. Drag an instance of the TextArea component from the User Interface tree in the Components panel onto the Stage. Place it next to the Loader component. Enter 125, 5 for the x, y coordinates respectively. Enter description_ta for the instance name. Set the Width to 200 and Height to 130. Click the Parameters tab in the Property inspector. For editable, select false. For html, select true. For wordWrap, select true.
Add an event listener to trigger the display of gift details Next you will add an event listener to the products_dg DataGrid instance to display information about each product. When the user clicks a product in the Gift Ideas section, a pop-up window appears with information about the product. ■ In the Actions panel of the main Timeline, add the following code: // Create a listener for the DataGrid to detect when the row in the // DataGrid is changed var dgListener:Object = new Object(); dgListener.
Add code to the ProductForm movie clip Next, you will add ActionScript to the ProductForm movie clip that you just created. The ActionScript populates the components in the movie clip with information about the selected gift, and adds an event listener to the Add to Cart button that adds the selected product to the cart. For more information on working with event listeners, see “Using event listeners” in Using ActionScript in Flash. 1.
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.
Create the checkout screen When the user clicks the Checkout button on the main screen, the Checkout screen appears. The Checkout screen provides forms where the user can enter billing, shipping, and credit card information. The checkout screen looks like the following: The checkout interface consists of components placed on a keyframe at Frame 10 in the application. You will use the Accordion component to create the checkout interface.
4. Drag an instance of the Button component from the User Interface tree in the Components panel onto the lower-right corner of the Stage. In the Property inspector, enter back_button for the instance name. Click the Parameters tab, and enter Back for the label property. About the Billing, Shipping, and Credit Card panes The Billing, Shipping, and Credit Card Information panes are built with movie clip instances that are displayed in the Accordion component instance.
8. In the Create New Symbol dialog box, enter checkout1_sub_mc for Name and select Movie Clip for Type. 9. 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. 10. Drag six instances of the Label component onto the Stage.
13. Select Frame 1 of the new layer. 14. In the Tools panel, select the Rectangle tool. Set the Stroke color to None and the Fill color to white. Click the Stroke Color control in the Tools panel and click the None button—the white swatch with a red line through it. Click the Fill Color control and click the white color swatch. 15. Drag to create a rectangle that extends beyond the bottom and right edges of the Label and TextInput instances.
Create the Credit Card Information pane The movie clips for the Credit Card Information pane are also similar to those for the Billing and Shipping Information panes. However, the nested movie clip for the Credit Card Information pane has somewhat different fields than the other two panes, for credit card number and other card data. 1.
7. Drag an instance of the Button component onto the Stage and position it at the bottom of the form, below the ccMonth_cb instance. Name the new instance checkout_button. Set the x and y coordinates to 125, 135. In the Property inspector’s Parameters tab, set the label property to Checkout. 8. Follow the instructions in steps 14-15 of the Billing Information instructions (see “Create the Billing Information pane” on page 40) to add a rectangle to the bottom of the form.
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.
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.
checkout_lv.ccMonth = thisChild3.ccMonth_cb.selectedItem; checkout_lv.ccYear = thisChild3.ccYear_cb.selectedItem; /* Send the variables from the checkout_lv LoadVars to the remote script on the server. Save the results in the response_lv instance. */ checkout_lv.sendAndLoad("http://www.flash-mx.com/mm/firstapp/ cart.cfm", response_lv, "POST"); response_lv.onLoad = function(success:Boolean) { evt.target.enabled = true; }; }; thisChild3.checkout_button.addEventListener("click", checkoutListener); cart_mc.
Creating an Application with Components (Flash Professional Only)
3 CHAPTER 3 Working with Components In this chapter, you’ll use several Macromedia Flash (FLA) files and ActionScript class files to learn how to add components to a document and set their properties. This chapter also explains a few advanced topics such as using code hints, creating custom focus navigation, managing component depth, and upgrading version 1 components to version 2 of the Macromedia Component Architecture. The files used in this chapter are TipCalulator.fla and TipCalculator.swf.
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.) To display the Components panel: ■ Select Window > Components. Components panel menu To display components that were installed after Flash starts: 1. Select Window > Components. 2. Select Reload from the Components panel pop-up menu.
Adding components during authoring You can add a component to a document by using the Components panel, and then add additional instances of the component to the document by dragging the component from the Library panel to the Stage. You can set properties for additional instances in the Parameters tab of the Property inspector or in the Parameters tab in the Component inspector. To add a component to a Flash document by using the Components panel: 1. Select Window > Components. 2.
8. Change the size of the component as desired by editing the values for the width and height. For more information on sizing specific component types, see the individual component entries in Components Language Reference. 9. If you want to change the color and text formatting of a component, do one or more of the following: Set or change a specific style property value for a component instance by using the setStyle() method, which is available to all components. For more information, see UIObject.
Alternatively, you can use the full package path, as follows: mx.controls.Alert.show("The connection has failed", "Error"); For more information, see “About importing class files” in Learning ActionScript 2.0 in Flash. You can use ActionScript methods to set additional parameters for dynamically added components. For more information, see 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.
Components in the Library panel When you add a component to a document, it is displayed as a compiled clip (SWC file) symbol in the Library panel. A ComboBox component in the Library panel 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.
Setting component parameters Each component has parameters that you can set to change its appearance and behavior. A parameter is a property that appears in the Property inspector and Component inspector. The most commonly used properties appear as authoring parameters; others must be set with ActionScript. All parameters that can be set during authoring can also be set with ActionScript. Setting a parameter with ActionScript overrides any value set during authoring.
To enter parameters for a component instance in the Component inspector: 1. Select Window > Component Inspector. 2. Select an instance of a component on the Stage. 3. To enter parameters, click the Parameters tab. 4. To enter or view bindings or schemas for a component, click their respective tabs. For more information, see “Data Integration (Flash Professional Only)” in Using Flash. Sizing components Use the Free Transform tool or the setSize() method to resize component instances.
You can call the setSize() method from any component instance (see UIObject.setSize() on page 1341) to resize it. The following code resizes the TextArea component to 200 pixels wide and 300 pixels high: myTextArea.setSize(200, 300); NO TE 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.
Using code hints When you are using ActionScript 2.0, you can use strict typing for a variable that is based on a built-in class, including component classes. If you do so, the ActionScript editor displays code hints for the variable. For example, suppose you type the following: import mx.controls.CheckBox; var myCheckBox:CheckBox; myCheckBox.
If nothing on the Stage has a tab index value, the Focus Manager uses the depth levels (zorder). The depth levels are set up primarily by the order in which components are dragged to the Stage; however, you can also use the Modify > Arrange > Bring to Front/Send to Back commands to determine the final z-order. To give focus to a component in an application, call focusManager.setFocus(). To create a button that receives focus when a user presses Enter (Windows) or Return (Macintosh), set the FocusManager.
Components in Live Preview The Live Preview feature, enabled by default, lets you view components on the Stage as they will appear in the published Flash content; the components appear at their approximate size. The live preview reflects different parameters for different components. For information about which component parameters are reflected in the live preview, see each component entry in the Components Language Reference.
To change the export frame for all your classes: 1. Select File > Publish Settings. 2. In the Flash tab of the Publish Settings dialog box, make sure the ActionScript version is set to ActionScript 2.0. 3. Click the Settings button to the right of the ActionScript version. 4. In ActionScript 2.0 Settings, change the number for the Export Frame for Classes text box to the frame where your components first appear.
About loading components If you load version 2 components into a SWF file or into the Loader component, the components may not work correctly. These components include the following: Alert, ComboBox, DateField, Menu, MenuBar, and Window. Use the _lockroot property when calling loadMovie() or loading into the Loader component. If you’re using the Loader component, add the following code: myLoaderComponent.content.
4 CHAPTER 4 Handling Component Events Every component has events that are broadcast when a user interacts with it (for example, the click and change events) or when something significant happens to the component (for example, the load event). To handle an event, you write ActionScript code that executes when the event occurs. Each component broadcasts its own set of events. This set includes the events of any class from which the component inherits.
Using listeners to handle events The version 2 component architecture has a broadcaster/listener event model. (A broadcaster is sometimes also referred to as a dispatcher.) It is important to understand the following key points about the model: ■ All events are broadcast by an instance of a component class. (The component instance is the broadcaster.) ■ A listener can be a function or an object. If the listener is an object, it must have a callback function defined on it.
Using listener objects To use a listener object, you can either use the this keyword to specify the current object as the listener, use an object that already exists in your application, or create a new object. ■ Use this in most situations. It’s often easiest to use the current object (this) as a listener, because its scope contains the components that need to react when the event is broadcast. ■ Use an existing object if it is convenient.
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.
8. In the Actions panel, enter the following code: var myButton:mx.controls.Button; var myText:mx.controls.TextInput; 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. To register a listener object in a class (AS) file: 1. Open the file TipCalculator.
Using the handleEvent callback function You can also use listener objects that support a handleEvent function. Regardless of the name of the event that is broadcast, the listener object’s handleEvent method is called. You must use an if..else or a switch statement to handle multiple events. For example, the following code uses an if..
Using listener functions Unlike the handleEvent syntax, several listener functions can handle different events. So instead of having the if and else if checks in myHandler, you can just define myChangeHandler for the change event and myScrollHandler for the scroll event and register them, as shown here: myList.addEventListener("change", myChangeHandler); myList.
To register a listener object in a Flash (FLA) file: 1. In Flash, select File > New and create a new Flash document. 2. Drag a List component to the Stage from the Components panel. 3. In the Property inspector, enter the instance name myList. 4. Select Frame 1 in the Timeline. 5. Select Window > Actions. 6. In the Actions panel, enter the following code: // declare variables var myList:mx.controls.List; var myHandler:Function; // add items to the list myList.addItem("Bird"); myList.
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 A U T IO N 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.
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.
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 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.
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.
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 onLoad() { myCheckBox_chb.addEventListener("click", Delegate.create(this, chb_onClick)); myButton_btn.addEventListener("click", Delegate.
Delegating the scope of a function The addEventListener() method requires two parameters: the name of an event and a reference to a listener. The listener can either be an object or a function. If you pass an object, the callback function assigned to the object is invoked in the scope of the object. However, if you pass a function, the function is invoked in the scope of the component instance that calls addEventListener(). (For more information, see “About scope in listeners” on page 71.
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.
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 = new Object(); listener.
To use the on() event handler: 1. Drag a User Interface component to the Stage. For example, drag a Button component to the Sage. 2. On the Stage, select the component and open the Actions panel. 3. Add the on() handler to the Actions panel in the format: on(event){ //your statements go here } 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.
Handling Component Events
5 CHAPTER 5 Customizing Components 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.
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 Components Language Reference).
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).
■ Create custom style declarations and apply them to several component instances. You may want to have groups of components in a document share a style. To do this, you can create custom style declarations to apply to the components you specify. For more information, see “Setting custom styles for groups of components” on page 87. ■ Create default class style declarations. You can define a default class style declaration so that every instance of a class shares a default appearance.
You can also access the styles directly as properties (for example, myButton.color = 0xFF00FF). 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.
To create a component instance and set multiple properties simultaneously using ActionScript: 1. Drag a component to the library. 2. Open the Actions panel and select Scene 1, then select Layer 1: Frame 1. 3.
To change one or more properties in the global style declaration: 1. Make sure the document contains at least one component instance. For more information, see “Adding components to Flash documents” on page 50. 2. Select a frame in the Timeline on which (or before which) the components appear. 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.
To create a custom style declaration for a group of components: 1. Add at least one component to the Stage. For more information, see “Adding components to Flash documents” on page 50. This example uses three button components with the instance names a, b, and c. If you use different components, give them instance names in the Property inspector and use those instance names in step 8. 2. Select a frame in the Timeline on which (or before which) the component appears. 3. Open the Actions panel. 4.
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").
Setting inheriting styles on a container An inherited style is a style that inherits its value from parent components in the document’s MovieClip hierarchy. If a text or color style is not set at an instance, custom, or class level, Flash searches the MovieClip hierarchy for the style value. Thus, if you set styles on a container component, the contained components inherit these style settings.
To create an Accordion component with styles that are inherited by the components in the individual Accordion panes: 1. Open a new FLA file. 2. Drag an Accordion component from the Components panel to the Stage. 3. Use the Property inspector to name and size the Accordion component. For this example, give the component the instance name accordion. 4. Drag a TextInput component and a Button component from the Components panel to the library.
Using global, custom, and class styles in the same document If you define a style in only one place in a document, Flash uses that definition when it needs to know a property’s value. However, one Flash document can have a variety of style settings—style properties set directly on component instances, custom style declarations, default class style declarations, inheriting styles, and a global style declaration.
Color names are strings that map to commonly used colors. You can add new color names by using the Style Manager (see StyleManager class in the Components Language Reference).
Customizing component animations Several components, such as the Accordion, ComboBox, and Tree components, provide animation to demonstrate the transition between component states—for example, when switching between Accordion children, expanding the ComboBox drop-down list, and expanding or collapsing Tree folders. Additionally, components provide animation related to the selection and deselection of an item, such as rows in a list.
Easing class Description 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: Easing method Description easeIn Provides the easing effect at the beginning of the transition.
About skinning components Skins are movie clip symbols a component uses to display its appearance. Most skins contain shapes that represent the component’s appearance. Some skins contain only ActionScript code that draws the component in the document. Version 2 components are compiled clips—you cannot see their assets in the library. However, the Flash installation includes FLA files that contain all the component skins. These FLA files are called themes.
Choose one of the following ways to skin a component according to what you want to do. These approaches are listed from easiest to most difficult. ■ To change the skins associated with all instances of a particular component in a single document, copy and modify individual skin elements. (See “Editing component skins in a document” on page 97). This method of skinning is recommended for beginners, because it doesn’t require any scripting.
To edit component skins in a document: 1. If you already applied the Sample theme to a document, skip to step 5. 2. Select File > Import > Open External Library, and select the SampleTheme.fla file. This file is located in the application-level configuration folder. For the exact location on your operating system, see “About themes” on page 108. 3.
Creating new component skins If you want to use a particular skin for one instance of a component, but another skin for another instance of the component, you must open a theme FLA file and create a new skin symbol. Components are designed to make it easy to use different skins for different instances. To create a new skin: 1. Select File > Open and open the theme FLA file that you want to use as a template. 2. Select File > Save As and select a unique name, such as MyTheme.fla. 3.
Linking skin color to styles The version 2 component framework makes it easy to link a visual asset in a skin element to a style set on the component using the skin. To register a movie clip instance to a style, or an entire skin element to a style, add ActionScript code in the timeline of the skin to call mx.skins.ColoredSkinElement.setColorStyle(targetMovieClip, styleName). To link a skin to a style property: 1. If you already applied the Sample theme to a document, skip to step 5. 2.
8. Add ActionScript code to register the skin element or a movie clip instance it contains as a colored skin element. For example, add the following code to the skin element’s Timeline. mx.skins.ColoredSkinElement.setColorStyle(innerCircle, "symbolBackgroundDisabledColor"); In this example you’re using a color that already corresponds to an existing style name in the Sample style.
To dynamically create a component and apply a new skin: 1. Select File > New to create a new Flash document. 2. Select File > Save and give the file a unique name, such as DynamicSkinning.fla. 3. Drag any components from the Components panel to the library, including the component whose skin you edited (in this example, RadioButton). This adds the symbols to the document’s library, but doesn’t make them visible in the document. 4. Drag MyRadioTrueUp and any other symbols you customized from MyTheme.
Applying new skins to a subcomponent In certain situations you may want to modify the skins of a subcomponent in a component, but the skin properties are not directly available (for example, there is no direct way to alter the skins of the scroll bar in a List component). The following code lets you access the scroll bar skins. All the scroll bars that are created after this code runs will also have the new skins.
■ If you want to change a specific scroll bar in a document, enter the following code in the Actions panel on Frame 1 of the Timeline: import mx.controls.List import mx.controls.scrollClasses.ScrollBar var oldName = ScrollBar.prototype.downArrowDownName; ScrollBar.prototype.downArrowDownName = "MyScrollDownArrowDown"; createClassObject(List, "myList1", 0, {dataProvider: ["AL","AR","AZ", "CA","HI","ID", "KA","LA","MA"]}); myList1.redraw(true); ScrollBar.prototype.downArrowDownName = oldName; NO T E 7.
8. Do one of the following to add a List component to the document: ■ ■ Drag a List component from the Components panel to the Stage. Enter enough label parameters so that the vertical scroll bar will appear. Drag a List component from the Components panel to the library. Enter the following code on Frame 1 of the main Timeline of SkinsInitExample.fla: createClassObject(mx.controls.
12. Enter the following code: import mx.controls.VScrollBar import mx.controls.List class MyVScrollBar extends VScrollBar{ function init():Void{ if (_parent instanceof List){ downArrowDownName = "MyScrollDownArrowDown"; } super.init(); } } 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.
6. Select the Export for ActionScript check box and click OK. Export in First Frame should be automatically selected; if it is not, select it. 7. Enter the following code in the Actions panel on Frame 1 of the MyComboBox symbol: #initclip 10 import MyComboBox Object.registerClass("ComboBox", MyComboBox); #endinitclip 8. When you finish editing the symbol, click the Back button at the left side of the information bar at the top of the Stage to return to document-editing mode. 9.
About themes Themes are collections of styles and skins. The default theme for Flash is called Halo (HaloTheme.fla). The Halo theme lets you provide a responsive, expressive experience for your users. Flash includes additional themes, like Sample (SampleTheme.fla). The Sample theme provides an example of how you can use more styles for customization. (The Halo theme does not use all styles included in the Sample theme.
To switch to the Sample theme: 1. Select File > Open and open the document that uses version 2 components in Flash, or select File > New and create a new document that uses version 2 components. 2. Select File > Import > Open External Library, and select SampleTheme.fla to apply to your document. This file is located in the application-level configuration folder. For the exact location on your operating system, see “About themes” on page 108. 3. In the SampleTheme.
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.
Creating a new theme If you don’t want to use the Halo theme or the Sample theme, you can modify one of them to create a new theme. Some skins in the themes have a fixed size. You can make them larger or smaller and the components will automatically resize to match them. Other skins are composed of multiple pieces, some static and some that stretch.
Modifying default style property values in a theme The default style property values are provided by each theme in a class named Default. To change the defaults for a custom theme, create a new ActionScript class called Default in a package appropriate for your theme, and change the default settings as desired. To modify default style values in a theme: 1. Create a new folder for your theme in First Run/Classes/mx/skins. For example, create a folder called myTheme. 2.
16. Locate the FocusRect symbol. In this example, it’s in Flash UI Components 2/Themes/MMDefault/FocusRect. 17. Edit the symbol properties for the FocusRect symbol. 18. Change the AS 2.0 Class setting to reflect your new package. The example class is mx.skins.myTheme.FocusRect. 19. Click OK. 20.Apply the custom theme to a document by following the steps in the next section. Remember to include the Defaults and FocusRect symbols when dragging assets from your custom theme to the target document.
3. In the theme’s Library panel, select Flash UI Components 2/Themes/MMDefault and drag the Assets folders for any components you want to use to your document’s library. For example, drag the RadioButton Assets folder to your library. If you’re unsure which components are in the document, drag the entire theme movie clip (for example, for the SampleTheme.fla, the main theme movie clip is Flash UI Components 2 > SampleTheme) to the Stage. The skins are automatically assigned to components in the document.
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.
Changing export settings When you apply the Sample or Halo theme to your document, many of the skin assets are set to export in the first frame in order to make them immediately available to the components during playback.
Halo theme ■ Flash UI Components 2/Base Classes/UIObject ■ Flash UI Components 2/Themes/MMDefault/Defaults ■ Flash UI Components 2/Base Classes/UIObjectExtensions ■ Flash UI Components 2/Component Assets/BoundingBox ■ Flash UI Components 2/HaloTheme ■ Flash UI Components 2/Themes/MMDefault/Accordion Assets/ AccordionHeaderSkin ■ Flash UI Components 2/Themes/MMDefault/Alert Assets/AlertAssets ■ Flash UI Components 2/Themes/MMDefault/Border Classes/Border ■ Flash UI Components 2/Themes/MMDefa
■ ■ Flash UI Components 2/Themes/MMDefault/ScrollBar Assets/VScrollBarAssets Flash UI Components 2/Themes/MMDefault/Stepper Assets/Elements/ StepThemeColor1 ■ Flash UI Components 2/Themes/MMDefault/Stepper Assets/NumericStepperAssets ■ Flash UI Components 2/Themes/MMDefault/Tree Assets/TreeAssets ■ Flash UI Components 2/Themes/MMDefault/Window Assets/Window Assets Combining skinning and styles to customize a component In this section, you will customize a combo box component instance using styles, t
Creating the new style declaration Now, you need to create a new style declaration and assign styles to the style declaration. After you have all the styles you want in the style declaration, you can assign the new style name to the combo box instance. To create a new style declaration and give it a name: 1.
Assigning style definitions to the combo box At this point, you have a style declaration containing a variety of styles, but you need to explicitly assign the style name to the component instance. You can assign this new style declaration to any component instance within your document in the following manner. Add the following line after the addItem() statements for my_cb (as a coding convention, you should keep all your combo box construction statements together): my_cb.
To change the theme for the styled component: 1. Select File > Import > Open External Library, and select SampleTheme.fla to open the Sample theme library in Flash. This file is located in the application-level configuration folder: ■ ■ 2.
When you edit a component skin symbol: ■ All instances of that component will use new skins (but not custom styles unless you explicitly attach the styles to the instances), and some components dependent on that component will use the new skins. ■ If you assign a new theme after you’ve edited your component skins, make sure you don’t overwrite the existing “edited” skins (a dialog box asks if you want to overwrite the skins and gives you an opportunity to stop Flash from overwriting the skins).
3. Double-click the down arrow (black triangle) to edit it. N OT E 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. 5. While still editing SymDownArrow, draw a circle in the place where the down arrow had been.
6. Select Control > Test Movie to see the skinned combo box: In your document’s library, if you select ComboDownArrowOver and ComboDownArrowUp, you’ll see that they also have the blue circle instead of the black triangle, because they also use SymDownArrow for the down arrow symbol.
6 CHAPTER 6 Creating Components This chapter describes how to create your own component and package it for distribution. This chapter contains the following sections: Component source files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 Overview of component structure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 Building your first component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
■ ActionScript class files ■ In Windows: C:\Program Files\Macromedia\Flash 8\language\First Run\Classes\mx ■ On the Macintosh: HD/Applications/Macromedia Flash 8/First Run/Classes/mx Overview of component structure A component consists of a Flash (FLA) file and an ActionScript (AS) file. You can optionally create and package other files (for example, an icon and a .swd debugging file) with your component, but all components require a FLA and an ActionScript file.
It’s a good idea to save the component’s FLA and AS files in the same folder and give them the same name. If the AS file is not saved in the same folder, you must verify that the folder is in the classpath so the FLA file can find it. For more information about the classpath, see “Classes” in Learning ActionScript 2.0 in Flash. Building your first component In this section, you will build a Dial component. The completed component files, Dial.fla, Dial.as, and DialAssets.
4. If the Linkage section of the Create New Symbol dialog box isn’t open, click the Advanced button to reveal it. 5. In the Linkage area, select Export for ActionScript and deselect Export in First Frame. 6. In the Identifier text box, enter a linkage identifier such as Dial_ID. 7. in the AS 2.0 Class text box, enter Dial. This value is the component class name. If the class is in a package (for example, mx.controls.Button), enter the entire package name. 8. Click OK.
14. In the Assets layer, select Frame 2 and drag an instance of UIComponent to the Stage. 15. Close the StandardComponents.fla library. 16. Select File > Import > Open External Library and select the DialAssets.fla file. ■ ■ 17. In Windows: C:\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\Components\DialComponent\DialAssets.fla. On the Macintosh: HD/Applications/Macromedia Flash 8/Samples and Tutorials/ Samples/Components/DialComponent/DialAssets.
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 23.Save OK. the file. Creating the Dial class file Now, you need to create the Dial class file as a new ActionScript file. To create the Dial class file: 1. In Flash, select File > New and then select ActionScript File. 2. Select File > Save As and save the file as Dial.
// The private member variable "__value" is publicly // accessible through implicit getter/setter methods, // Updating this property updates the needle's position // when the value is set. private var __value:Number = 0; // This flag is set when the user drags the // needle with the mouse, and cleared afterwards. private var dragging:Boolean = false; // Constructor; // While required for all classes, v2 components require // the contstructor to be empty with zero arguments.
// The size() method is invoked when the component's size // changes. This is an opportunity to resize the children, // and the dial and needle graphics. // The size() method is required for components extending UIComponent. function size():Void { super.size(); dial._width = width; dial._height = height; // Cause the needle to be redrawn, if necessary. invalidate(); } // This is the getter/setter for the value property. // The [Inspectable] metadata makes the property appear // in the Property inspector.
} // Remove the mouse events when the drag is complete // and clear the flag. function mouseUpHandler() { dragging = false; delete onMouseMove; delete onMouseUp; } function mouseMoveHandler() { // Calculate the angle if (dragging) { var x:Number = _xmouse - width/2; var y:Number = _ymouse - height/2; var oldValue:Number = value; var newValue:Number = 90+180/Math.PI*Math.
To test the Dial component: 1. In the Dial.fla file, select the Dial component in the library, open the Library context menu (Windows: Right-click; Mac: control-click), and select Convert to Compiled Clip. A compiled clip is added to the library with the name Dial SWF. NO TE 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.
To export the Dial component: 1. In the Dial.fla file, select the Dial component in the library, open the Library context menu (Windows: Right-click; Mac: control-click), and select Export SWC File. 2. Select a location to save the SWC file. If you save it to the Components folder in the user-level configuration folder, you can reload the Components panel without restarting Flash and the component appears in the panel.
Selecting a parent class The first thing to decide when creating a component is whether to extend one of the version 2 classes. If you choose to extend a version 2 class, you can either extend a component class (for example, Button, CheckBox, ComboBox, List, and so on) or one of the base classes, UIObject or UIComponent. All the component classes, except the Media components, extend the base classes; if you extend a component class, the class automatically inherits from the base classes as well.
Understanding the UIObject class Components based on version 2 of the Macromedia Component Architecture descend from the UIObject class, which is a subclass of the MovieClip class. The MovieClip class is the base class for all classes in Flash that represent visual objects on the screen. UIObject adds methods that allow you to handle styles and events. It posts events to its listeners just before drawing (the draw event is the equivalent of the MovieClip.
The following figure shows the version 2 component hierarchy: Version 2 component hierarchy A FlashPaper version of this file is available in the Flash installation directory at this location: Flash 8\Samples and Tutorials\Samples\Components\arch_diagram.swf. About extending the MovieClip class You can choose not to extend a version 2 class and have your component inherit directly from the ActionScript MovieClip class.
Inserting a new movie clip symbol All components are MovieClip objects. To create a new component, you must first insert a new symbol into a new FLA file. To add a new component symbol: 1. In Flash, create a blank Flash document. 2. Select Insert > New Symbol. The Create New Symbol dialog box appears. 3. Enter a symbol name. Name the component by capitalizing the first letter of each word in the component (for example, MyComponent). 4. Select the Movie Clip behavior. 5.
A component’s symbol should have two layers. This section describes what layers to insert and what to add to those layers. To edit the movie clip: 1. Rename Layer 1 Actions and select Frame 1. 2. Open the Actions panel and add a stop() function, as follows: stop(); Do not add any graphical assets to this frame. 3. Add a Layer named Assets. 4. On the Assets layer, select Frame 2 and insert a blank keyframe. There are now two blank keyframes in this layer. 5.
6. If you are extending an existing component, place an instance of that component and any other base classes in Frame 2 of the Assets layer. To do this, select the symbol from the Components panel and drag it to the Stage. If you are extending a base class, open StandardComponents.fla from the Configuration/ ComponentFLA folder and drag the class from the library to the Stage. N OT E 7. When you drag UIComponent to the component library, the folder hierarchy in the library is changed.
To define a movie clip as a component: 1. Select the movie clip in the library and select Component Definition from the Library context menu (Windows: Right-click; Mac: control-click). 2. You must enter an AS 2.0 class. If the class is part of a package, enter the full package name. 3. Specify other options in the Component Definition dialog box, if desired: ■ Click the Plus (+) button to define parameters. This is optional.
Creating the ActionScript class file All component symbols are linked to an ActionScript 2.0 class file. (For information on linking, see “Creating a component movie clip” on page 138.) To edit ActionScript class files, you can use Flash, any text editor, or any Integrated Development Environment (IDE). The external ActionScript class extends another class (whether the class is a version 2 component, a version 2 base class, or the ActionScript MovieClip class).
function init():Void { super.init(); boundingBox_mc.width = 0; boundingBox_mc.height = 0; boundingBox_mc.visible = false; } function createChildren():Void{ // Call createClassObject to create subobjects. size(); invalidate(); } function size(){ // Write code to handle sizing. super.size(); invalidate(); } function draw(){ // Write code to handle visual representation. super.
4. Define member variables. (See “Defining variables” on page 148). These can be used in getter/setter methods. 5. Define a constructor function. (See “About the constructor function” on page 164). 6. Define an init() method. (See “Defining the init() method” on page 162). This method is called when the class is created if the class extends UIComponent. If the class extends MovieClip, call this method from the constructor function. 7. Define a createChildren() method.
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; class MyComponent extends UIComponent{ You can also use the wildcard character (*) to import all the classes in a given package.
Identifying the class, symbol, and owner names To help Flash find the proper ActionScript classes and packages and to preserve the component’s naming, you must set the symbolName, symbolOwner, and className variables in your component’s ActionScript class file. The symbolOwner variable is an Object reference that refers to a symbol. If the component is its own symbolOwner or is the symbolOwner has been imported, it does not have to be fully qualified.
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.
Getter/setter methods are a straightforward way to detect changes to component properties. Instead of declaring a regular variable with var, declare getter/setter methods, as follows: private var __flavorStr:String = "strawberry"; [Inspectable(defaultValue="strawberry")] public function get flavorStr():String{ return __flavorStr; } public function set flavorStr(newFlavor:String) { __flavorStr = newFlavor; invalidate(); } The invalidate() call causes the component to redraw itself with the new flavor.
In the following example, the Inspectable tags define the flavorStr, colorStr, and shapeStr parameters: [Inspectable(defaultValue="strawberry")] public var flavorStr:String; [Inspectable(defaultValue="blue")] public var colorStr:String; [Inspectable(defaultValue="circular")] public var shapeStr:String; In the Property inspector and the Parameters tab of the Component inspector, Flash displays all of these parameters as type String.
About the Inspectable tag You use the Inspectable tag to specify the user-editable (inspectable) parameters that appear in the Component inspector and Property inspector. This lets you maintain the inspectable properties and the underlying ActionScript code in the same place. To see the component properties, drag an instance of the component onto the Stage and select the Parameters tab of the Component inspector. Collection parameters are also inspectable.
The Inspectable tag also supports loosely typed attributes like this: [Inspectable("danger", 1, true, maybe)] The metadata statement must immediately precede the property’s variable declaration in order to be bound to that property. The following table describes the attributes of the Inspectable tag: Attribute Type Description defaultValue String or Number (Optional) A default value for the inspectable property.
About the InspectableList tag Use the InspectableList tag to specify which subset of inspectable properties should appear in the Property inspector. Use InspectableList in combination with Inspectable so that you can hide inherited attributes for components that are subclasses. If you do not add an InspectableList tag to your component’s class, all inspectable parameters, including those of the component’s parent classes, appear in the Property inspector.
To broadcast a particular instance, call the dispatchEvent() method. See “Using the dispatchEvent() method” on page 166. About the Bindable tag Data binding connects components to each other. You achieve visual data binding through the Bindings tab of the Component inspector. From there, you add, view, and remove bindings for a component. Although data binding works with any component, its main purpose is to connect user interface components to external data sources, such as web services and XML documents.
The Bindable tag takes three options that specify the type of access to the property, as well as the data type of that property. The following table describes these options: Option Description readonly Indicates that when you create bindings in the Component inspector, you can only create bindings that use this property as a source. However, if you use ActionScript to create bindings, there is no such restriction.
About the ChangeEvent tag The ChangeEvent tag tells data binding that the component will generate an event any time the value of a specific property changes. In response to the event, data binding executes any binding that has that property as a source. The component only generates the event if you write appropriate ActionScript code in the component. The event should be included in the list of Event metadata declared by the class. You can declare a property by using var or getter/setter methods.
About the Collection tag Use the Collection tag to describe an array of objects that can be modified as a collection of items in the Values dialog box while authoring. The type of the objects is identified by the collectionItem attribute. A collection property contains a series of collection items that you define in a separate class. This class is either mx.utils.CollectionImpl or a subclass of it.
The following table describes the attributes of the Collection tag: Attribute Type Description name String (Required) Name that appears in the Component inspector for the collection. variable String (Required) ActionScript variable that points to the underlying Collection object (for example, you might name a Collection parameter Columns, but the underlying variable attribute might be __columns).
The ComponentTask tag has the following syntax: [ComponentTask [taskName,taskFile [,otherFile[,…]]] The taskName and taskFile attributes are required. The otherFile attribute is optional The following example associates SetUp.jsfl and AddNewSymbol.jsfl with the component class named myComponent. The AddNewSymbol.jsfl requires a testXML.xml file and is specified in the otherFile attribute. [ComponentTask("Do Some Setup","SetUp.jsfl")] [ComponentTask("Add a new Symbol","AddNewSymbol.jsfl","testXML.
The following example sets several component parameters in the JellyBean class file, and exposes them with the Inspectable tag in the Component inspector: class JellyBean{ // a string parameter [Inspectable(defaultValue="strawberry")] public var flavorStr:String; // a string list parameter [Inspectable(enumeration="sour,sweet,juicy,rotten",defaultValue="sweet") ] public var flavorType:String; // an array parameter [Inspectable(name="Flavors", defaultValue="strawberry,grape,orange", verbose=1, category="Frui
About core functions You must define five functions in the component class file: init(), createChildren(), the constructor function, draw(), and size(). When a component extends the UIComponent, these five functions in the class file are called in the following order: ■ init() Any initialization occurs during the init() function call. For example, instance member variables can be set at this time and the component bounding box can be hidden.
Defining the init() method Flash calls the init() method when the class is created. This method is called only once when a component is instantiated. You should use the init() method to do the following: ■ Call super.init(). This is required. ■ Make the boundingBox_mc invisible. boundingBox_mc.width = 0; boundingBox_mc.height = 0; boundingBox_mc.visible = false; ■ Create instance member variables. The width, height, and clip parameters are properly set only after this method is called.
The following table describes the parameters: Parameter Type Description className Object The name of the class. instanceName String The name of the instance. depth Number The depth for the instance. initObject Object An object that contains initialization properties. To call createClassObject(), you must know what the children are, because you must specify the name and type of the object, plus any initialization parameters in the call to createClassObject().
About the constructor function You can recognize a constructor function because it has the same name as the component class. For example, the following code shows the ScrollBar component’s constructor function: function ScrollBar() { } In this case, when a new scroll bar is instantiated, the ScrollBar() constructor is called. Generally, component constructors should be empty. Setting properties in constructors can sometimes lead to overwriting default values, depending on the order of initialization calls.
Defining the draw() method You can write code in the draw() method to create or modify visual elements of a component. In other words, in the draw() method, a component draws itself to match its state variables. Since the last draw() method was called, multiple properties or methods may have been called, and you should try to account for all of them in the body of draw(). However, you should not call the draw() method directly.
About invalidation Macromedia 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.) You must call an invalidation method at least once during the instantiation of your component.
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.
In addition, because of inheritance from the base classes, all components broadcast the following events: UIComponent event Description load The component is creating or loading its subobjects. unload The component is unloading its subobjects. focusIn The component now has the input focus. Some HTML-equivalent components (ListBox, ComboBox, Button, Text) might also broadcast focus, but all broadcast DOMFocusIn. focusOut The component has lost the input focus.
The following example shows the skin variables for the various states of the CheckBox component: var var var var var var var var var var var var var var var var falseUpSkin:String = ""; falseDownSkin:String = ""; falseOverSkin:String = "" falseDisabledSkin:String = ""; trueUpSkin:String = ""; trueDownSkin:String = ""; trueOverSkin:String = ""; trueDisabledSkin:String = ""; falseUpIcon:String = "CheckFalseUp"; falseDownIcon:String = "CheckFalseDown"; falseOverIcon:String = "CheckFalseOver"; falseDisabledIco
To register a skin to a style: 1. Create a new ActionScript file and copy the following code into it: import mx.core.UIComponent; class Shape extends UIComponent{ static var symbolName:String = "Shape"; static var symbolOwner:Object = Shape; var className:String = "Shape"; var themeShape:String = "circle_skin" function Shape(){ } function init(Void):Void{ super.init(); } function createChildren():Void{ setSkin(1, themeShape); super.createChildren(); } } 2. Save the file as Shape.as. 3.
8. Open StandardComponents.fla as an external library, and drag the UIComponent movie clip to the Stage on the second frame of the Shape movie clip (with circle_skin). 9. Close StandardComponents.fla. 10. Select the Shape movie clip in the library, select Component Definition from the Library context menu (Windows: Right-click, Mac: control-click), and enter the AS 2.0 class name Shape. 11. Test the movie clip with the Shape component on the Stage.
Registering a new style name If you have created a new style name and it is a color style, add the new name to the colorStyles object in the StyleManager.as file (First Run\Classes\mx\styles\StyleManager.as).
Incorporating existing components within your component In this section, you will build a simple LogIn component that incorporates Label, TextInput and Button components. This tutorial demonstrates how existing components are incorporated in new components by adding their uncompiled Flash (FLA) library symbols. The completed component files, LogIn.fla, LogIn.as and LogIn.
6. Enter LogIn in the AS 2.0 Class text box. This value is the component class name. If you put the class in a package, enter the entire package name. For example, mx.controls.CheckBox denotes the CheckBox class in the mx.controls package. 7. Click OK. Flash opens in symbol-editing mode. 8. Insert a new layer. Name the top layer Actions and the bottom layer Assets. 9. Select Frame 2 in the Assets layer and insert a keyframe (F6).
■ ■ So that all assets are automatically copied into the library and are available to instantiate dynamically and access their methods, properties, and events. Placing assets in a frame ensures they are loaded more smoothly as the movie is streamed, so you do not need to set the assets in the library to be exported before the first frame. This method prevents an initial data transfer spike that could cause download delays or long pauses.
16. Use the Info panel to resize the BoundingBox to the size of the LogInFinal movie clip (340, 150), and position it at 0, 0. The BoundingBox instance is used to create the component’s live preview and allow the user to handle resize the component during authoring. You must set the size of the bounding box so that it can enclose all the graphical elements in your component.
[Event("click")] class LogIn extends UIComponent { /* Components must declare these member variables to be proper components in the components framework. */ static var symbolName:String = "LogIn"; static var symbolOwner:Object = LogIn; var className:String = "LogIn"; // The component's graphical representation.
name_label._y = 10; name_ti = createObject("TextInput", "name_ti", this.startDepth++,{_width:200,_heigh:22,_x:20,_y:30}); name_ti.html = false; name_ti.text = __name; name_ti.tabIndex = 1; /* Set this text input field to have focus. Note: Make sure to set select Control > Disable Keyboard Shortcuts in the Flash Debugger if it is not already selected, otherwise the focus may not set when testing. */ name_ti.setFocus(); name_label = createObject("Label", "password_label", this.
invalidate(); } /* Event Handler: Called by the LogIn button when it receives a mouse click. Since we want this event to be accessible outside of the scope of this component, The click event is dispatched using dispatchEvent. */ public function click(evt){ // Update the member variables with the input field contents. __name = name_ti.text; __password = password_ti.text; // Dispatch a click event when the button fires one. dispatchEvent({type:"click"}); } /* This is the getter/setter for the name property.
Testing and exporting the LogIn component You’ve created the Flash file that contains the graphical elements, the base classes and the class file that contains all the functionality of the LogIn component. Now it’s time to test the component. Ideally, you would test the component as you work, especially while you’re writing the class file. The fastest way to test as you work is to convert the component to a compiled clip and use it in the component’s FLA file.
For example the name and password would be passed to a web service which authenticates the name and password and returns a session ID and/or permission roles attributed to the user. */ myLoginValues.text = "Processing...\r"; myLoginValues.text += "Name: " + myLogin.name + " Password: " + myLogin.password; } myLogin.addEventListener("click",this); 3. Select Control > Test Movie to test the component in Flash Player.
Exporting and distributing a component Flash exports components as component packages (SWC files). Components may be distributed as SWC files or as FLA files. (See the article on Macromedia DevNet at www.macromedia.com/support/flash/applications/creating_comps/creating_comps12.html for information about distributing a component as a FLA.
File Description 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).
To export a SWC file for a completed component: 1. Select the component movie clip in the Flash library. 2. Right-click (Windows) or control-click (Mac) to open the Library context menu. 3. Select Export SWC File from the Library context menu. 4. Save the SWC file. Testing a SWC during development At different stages of development, it’s a good idea to export the component as a SWC and test it in an application.
Final steps in component development After you create the component and prepare it for packaging, you can add an icon and a tool tip. To make sure you completed all the necessary steps, you can also refer to the “Component development checklist” on page 186. Adding an icon You can add an icon that represents your component in the Components panel of the Flash authoring environment. To add an icon for your component: 1. Create a new image.
4. In the Component Definition dialog box, under Options, select Display in the Components Panel. The Tool tip text box becomes editable. 5. Enter the tooltip text for your component in the Tool tip text box. 6. Click OK to save the changes. Component development checklist When you design a component, use the following practices: ■ Keep the file size as small as possible. ■ Make your component as reusable as possible by generalizing functionality. ■ Use the RectBorder class (mx.skins.halo.
7 CHAPTER 7 Collection Properties When you create a new custom component in Macromedia 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.
You define collections and collection items as follows: ■ 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 157. ■ 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.
5. Add the utilities classes to your FLA file by selecting Window > Common Libraries > Classes and dragging UtilsClasses into the component’s library. UtilsClasses contains the mx.utils.* package for the Collection interface. NO T E 6. 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. Code a class that contains the collection item properties.
// You must code a reference to the collection item class // to force the compiler to include it as a dependency // within the SWC private var collItem:CompactDisc; // You must code a reference to the mx.utils.CollectionImpl class // to force the compiler to include it as a dependency // within the SWC private var coll:mx.utils.CollectionImpl; // required methods for all classes function init(Void):Void { super.init(); } function size(Void):Void { super.
This allows you to drag the MyShelf SWF file (the compiled clip that’s added to the library) into the MyShelf.fla file to test the component. Whenever you recompile the component, a Resolve Library Conflict dialog box appears, because an older version of the component already exists in the library. Choose to replace existing items. NO TE You should have already created the CompactDisc class; otherwise, you’ll get compiler errors when converting to a compiled clip.
Accessing collection information in a component class (AS) file In a component’s class file, you can write code that interacts with collection items defined during authoring or at runtime. To access collection item information in a component class file, you can use any of the following approaches. ■ The Collection tag includes a variable attribute, for which you specify a variable of type mx.utils.Collection.
Accessing collection items at runtime in a Flash application If a Flash application uses a component that has a collection property, you can access the collection property at runtime. This example adds several items to a collection property using the Values dialog box and displays them at runtime using the Collection and Iterator APIs. To access collection items at runtime: 1. Open the MyShelf.fla file that you created earlier. See “Simple collection example” on page 189.
Exporting components that have collections to SWC files When you distribute a component that has a collection, the SWC file must contain the following dependent files: ■ Collection interface ■ Collection implementation class ■ Collection item class ■ Iterator interface Of these files, your code typically uses the Collection and Iterator interfaces, which marks them as dependent classes. Flash automatically includes dependent files in the SWC file and output SWF file.
5. Click the Add (+) button and define a collection item. 6. Click the Add (+), Delete (-), and arrow buttons to add, modify, move, and delete collection items. 7. Click OK. For information on accessing a collection programmatically, see “Accessing collection items at runtime in a Flash application” on page 193.
Collection Properties
Index Numerics 9-slice not supported 19 A accessibility 20 ActionScript class files 143 audience for this document 8 B best practices for component development 186 Binding tab, in sample application (tutorial) 30 bitmap caching not supported 19 broadcaster 64 C class file about 144 example 143, 189 class keyword 146 class style sheets 82 classes and component inheritance 18 creating references to (tutorial) 25 creating.
class file example 143 class overview 144 className variable 147 common events 167 creating movie clips 138 creating subobjects 162 defining draw() method 165 defining init() method 162 defining parameters 159 defining size() method 165 defining variables 148 deleting 57 development checklist 186 dispatching events 166 editing movie clips 139 events 63 example of building a component 127, 173 example of class file with collection 189 exporting and distributing 182 exporting component as SWC 183 exporting SW
G M getter/setter methods 148 global style declarations 86 grids.
StandardComponents library 139 style declarations custom 87 default class 89 global 86 setting class 89 style properties, color 92 style sheets class 82 custom 82 styles about 82 creating components 169 determining precedence 92 setting 82 setting custom 87 setting global 86 setting on instance 84 using (tutorial) 27 See also individual component names subclasses, using to replace skins 106 subcomponents, applying skins 103 subobjects, creating 162 superclass keyword 146 SWC files about 19 and compiled clip