Using Action Script 3.0 Components
Using Action Script 3.0 Components
Using ActionScript 3.0 Components This user guide is protected under copyright law, 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. This guide is licensed for use under the terms of the Creative Commons Attribution Non-Commercial 3.0 License. This License allows users to copy, distribute, and transmit the guide for noncommercial purposes only so long as (1) proper attribution to Adobe is given as the owner of the guide; and (2) any reuse or distribution of the guide contains a notice that use of the guide is governed by these terms. The best way to provide notice is to include the following link. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ Adobe, the Adobe logo, ActionScript, and Flash are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries. Windows is either a registered trademark or trademark of Microsoft Corporation in the United States and/or other countries. Macintosh is a trademark of Apple Inc., registered in the United States and other countries. All other trademarks are the property of their respective owners. Updated Information/Additional Third Party Code Information available at www.adobe.com/go/thirdparty. Portions include software under the following terms: This product includes software developed by the Apache Software Foundation (http://www.apache.org/). This product includes software developed by Fourthought, Inc. (http://www.fourthought.com). MPEG Layer-3 audio compression technology licensed by Fraunhofer IIS and Thomson Multimedia (http://www.iis.fhg.de/amm/). This software is based in part on the work of the Independent JPEG Group. Speech compression and decompression technology licensed from Nellymoser, Inc. (www.nellymoser.com). Video in Flash Player is powered by On2 TrueMotion video technology. 1992-2005 On2 Technologies, Inc. All Rights Reserved. http://www.on2.com. This product contains either BSAFE and/or TIPEM software by RSA Security, Inc.
Sorenson Spark video compression and decompression technology licensed from Sorenson Media, Inc. 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 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.
iii
Contents
Chapter 1: Introduction Intended audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 System requirements .................................................................................................. 1 ............................................................................................. 1 ............................................................................................ 2 ............................................................................................. 2 About the documentation Typographical conventions Terms used in this manual Additional resources
.................................................................................................. 2
Chapter 2: About ActionScript 3.0 Components Benefits of using components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Component types ..................................................................................................... 4 ................................................................................... 6 .................................................................................... 8 ................................................................................. 8 Add to and delete from a document Find the version of the component A simple application ActionScript 3.0 event handling model
................................................................................................... 9
Chapter 3: Working with Components Component architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Working with component files Debug component applications Set parameters and properties The library Live Preview Sizing components Handling events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Work with the display list Work with FocusManager Work with a DataProvider Work with a CellRenderer
Chapter 4: Using the UI Components Use the Button component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Use the CheckBox component Use the ColorPicker component Use the ComboBox component Use the DataGrid component Use the Label component Use the List component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Use the NumericStepper component Use the ProgressBar component Use the RadioButton component
Use the ScrollPane component Use the Slider component Use the TextArea component Use the TextInput component Use the TileList component Use the UILoader component Use the UIScrollBar component
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Chapter 5: Customizing the UI Components About UI component customization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 Setting styles About Skins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Customize the ColorPicker component Customize the ComboBox component Customize the DataGrid component Customize the Label component Customize the List component
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Customize the NumericStepper component Customize the ProgressBar component Customize the RadioButton component Customize the ScrollPane component Customize the Slider component Customize the TextArea component Customize the TextInput component Customize the TileList component Customize the UILoader component Customize the UIScrollBar component
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Chapter 6: Using the FLVPlayback Component Use the FLVPlayback component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Customize the FLVPlayback component Use a SMIL file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Chapter 7: Using the FLVPlayback Captioning Component Use the FLVPlaybackCaptioning component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 Use Timed Text captions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 Use cue points with captioning
Chapter 1: Introduction
Adobe Flash CS5 Professional is the standard authoring tool 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 allow you to customize the component either during authoring in Flash or at run time with Adobe ActionScript methods, properties, and events. 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 allow you to easily and quickly build robust applications with a consistent appearance and behavior. This manual describes how to build applications with Adobe ActionScript 3.0 components. The Adobe ActionScript 3.0 Language and Components Reference describes each components application programming interface (API). You can use components created by Adobe, download components created by other developers, or create your own components.
Intended audience
This manual 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 run time, and use the event listener model to handle events. For more information, see Working with Components on page 16.
System requirements
Flash components do not have any system requirements beyond the system requirements for Flash. Any SWF file that uses Flash CS3 or later components must be viewed with Adobe Flash Player 9.0.28.0 or later, and must be published for ActionScript 3.0 (you can set this through File > Publish Settings, in the Flash tab).
Using Flash ActionScript 3.0 Developers Guide Adobe ActionScript 3.0 Reference for Flash Professional
Typographical conventions
The following typographical conventions are used in this manual:
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
In addition to the content in these manuals, Adobe provides regularly updated articles, design ideas, and examples at the Adobe Developer Center and the Adobe Design Center. You can find additional component samples at www.adobe.com/go/learn_fl_samples. Adobe Developer Center The Adobe Developer Center is your resource for up-to-the-minute information on ActionScript, articles about realworld application development, and information about important emerging issues. View the Developer Center at www.adobe.com/go/flash_devcenter. Adobe Design Center Learn the latest in digital design and motion graphics. Browse work by leading artists, discover new design trends, and hone your skills with tutorials, key workflows, and advanced techniques. Check back twice a month for fresh tutorials and articles, and inspirational gallery pieces. View the Design Center at www.adobe.com/go/fl_designcenter.
This section outlines some of the benefits of the ActionScript 3.0 components.
The power of ActionScript 3.0 provides a powerful, object-oriented programming language that is an important step
in the evolution of Flash Player capabilities. The language is designed for building rich Internet applications on a reusable code base. ActionScript 3.0 is based on ECMAScript, the international standardized language for scripting, and is compliant with the ECMAScript (ECMA-262) edition 3 language specification. For a thorough introduction to ActionScript 3.0, see ActionScript 3.0 Developers Guide. For reference information on the language, see the ActionScript 3.0 Reference.
FLA-based User Interface components provide easy access to skins for easy customizing while authoring. These
components also provide styles, including skin styles, that allow you to customize aspects of the components appearance and load skins at run time. For more information, see Customizing the UI Components on page 95 and the ActionScript 3.0 Reference.
New FVLPlayback component adds FLVPlaybackCaptioning component along with full screen support, improved live preview, skins that allow you to add color and alpha settings, and improved FLV download and layout features. The Property inspector and Component inspector allow you to change component parameters while authoring in
Flash. For more information, see Working with component files on page 18 and Set parameters and properties on page 20.
New collection dialog box for the ComboBox, List, and TileList components allows you to populate their
dataProvider property through the user interface. For more information, see Create a DataProvider on page 28.
The ActionScript 3.0 event model allows your application to listen for events and invoke event handlers to respond. For more information, see ActionScript 3.0 event handling model on page 8 and Handling events on page 23. Manager classes provide an easy way to handle focus and manage styles in an application. For more information, see the ActionScript 3.0 Reference. The UIComponent base class provides core methods, properties, and events to components that extend it. All of the
ActionScript 3.0 user interface components inherit from the UIComponent class. For more information see the UIComponent class in the ActionScript 3.0 Reference.
Use of a SWC in the UI FLA-based components provide ActionScript definitions as an asset inside the components
For more information, see the ActionScript 3.0 Reference. Note: Flash CS5 supports both FLA-based and SWC-based components. For more information, see Component architecture on page 16.
Component types
You install the Flash components when you install Flash CS5. ActionScript 3.0 components include the following user interface (UI) components:
Button CheckBox ColorPicker List NumericStepper RadioButton TextArea TextInput TileList
UILoader UIScrollBar
In addition to the user interface components, the Flash ActionScript 3.0 components include the following components and supporting classes:
The FLVPlayback Custom UI components, which are FLA-based and work with both the ActionScript 2.0 and
ActionScript 3.0 versions of the FLVPlayback component. For more information, see Using the FLVPlayback Component on page 131.
The FLVPlayback Captioning component, which provides closed captioning for FLVPlayback. See Using the
FLVPlayback Captioning Component on page 167. For a complete list of the ActionScript 3.0 components and their supporting classes, see the ActionScript 3.0 Reference. View Flash components: You can view the Flash ActionScript 3.0 components in the Components panel by following these steps.
1 Start Flash. 2 Create a new Flash file (ActionScript 3.0) or open an existing Flash document in which the Publish Settings specify
ActionScript 3.0.
3 Select Window > Components to open the Components panel, if it isnt already open.
You can also download additional components from the Adobe Exchange at www.adobe.com/go/flash_exchange. To install components downloaded from the Exchange, download and install the Adobe Extension Manager at www.adobe.com/go/exchange. Click the Adobe Exchange Home link and look for the Extension Manager link. Any component can appear in the Components panel in Flash. Follow these steps to install components on either a Windows or Macintosh computer. 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 CS5\language\Configuration\Components
On the Macintosh:
Macintosh HD:Applications:Adobe Flash CS5:Configuration:Components
3 Start Flash. 4 Select Window > Components to view the component in the Components panel if it isnt already open.
For more information about component files, see Working with component files on page 18
For more information, see Set parameters and properties on page 20.
7 Change the size of the component as desired by editing the values for the width (W:) and height (H:).
For more information on sizing specific component types, see Customizing the UI Components on page 95.
8 Select Control > Test Movie or press Control+Enter to compile the document and see the results of your settings.
You can also change the color and text formatting of a component by setting style properties for it or customize its appearance by editing the components skins. For more information on these topics, see Customizing the UI Components on page 95. If you drag a component to the Stage during authoring, you can refer to the component by using its instance name (for example, myButton).
For information on what package a component is in, see the ActionScript 3.0 Reference. For information about the location of component source files, see Working with component files on page 18. To create an instance of the component, you must invoke the components ActionScript constructor method. For example, the following statement creates an instance of a Button called aButton:
var aButton:Button = new Button();
The final step is to call the static addChild() method to add the component instance to the Stage or application container. For example, the following statement adds the aButton instance:
addChild(aButton);
At this point, you can use the components API to dynamically specify the components size and position on the Stage, listen for events, and set properties to modify its behavior. For more information on the API for a particular component, see the ActionScript 3.0 Reference. For more information on the addChild() method, see Work with the display list on page 24.
Delete a component
To delete a component instance from the Stage while authoring, simply select it and press the Delete key. This will remove the instance from the Stage but does not remove the component from your application. To delete a component from your Flash document after youve placed it on the Stage or in the library, you must delete it and its associated assets from the library. It isnt enough to delete the component from the Stage. If you dont remove it from the library, it will be included in your application when you compile it.
1 In the Library panel, select the symbol for the component. 2 Click the Delete button at the bottom of the Library panel, or select Delete from the Library panel menu.
Repeat these steps to delete any assets associated with the component. For information on how to remove a component from its container while your application is running, see Remove a component from the display list on page 25.
it aCb.
3 Press the F9 key or select Window > Actions to open the Actions panel. 4 Click Frame 1 on the main Timeline and add the following code to the Actions panel:
trace(aCb.version);
The version number, similar to the one in the following illustration, should appear in the Output panel. For the FLVPlayback and FLVPlaybackCaptioning components, you must refer to the class name rather than the instance name because the version number is stored in a class constant. Display the version number for the FLVPlayback and FLVPlaybackCaptioning components: 1 Create a new Flash file (ActionScript 3.0) document.
2 Drag the FLVPlayback and FLVPlaybackCaptioning components into the Library panel. 3 Press the F9 key or select Window > Actions to open the Actions panel. 4 Click Frame 1 on the main Timeline and add the following code to the Actions panel.
import fl.video.*; trace("FLVPlayback.VERSION: " + FLVPlayback.VERSION); trace("FLVPLaybackCaptioning.VERSION: " + FLVPlaybackCaptioning.VERSION);
To add event listeners in ActionScript 2.0, you use addListener() in some cases and addEventListener() in
others, whereas in ActionScript 3.0 you use addEventListener() in all cases.
There is no event flow in ActionScript 2.0, which means that the addListener() method can be called only on the
object that broadcasts the event, whereas in ActionScript 3.0 the addEventListener() method can be called on any object that is part of the event flow.
In ActionScript 2.0, event listeners can be either functions, methods, or objects, whereas in ActionScript 3.0, only
functions or methods can be event listeners.
The on(event) syntax is no longer supported in ActionScript 3.0, so you cannot attach ActionScript event code to
a movie clip. You can only use addEventListener() to add an event listener. The following example, which listens for a MouseEvent.CLICK event on a Button component called aButton, illustrates the basic ActionScript 3.0 event handling model:
aButton.addEventListener(MouseEvent.CLICK, clickHandler); function clickHandler(event:MouseEvent):void { trace("clickHandler detected an event of type: " + event.type); trace("the event occurred on: " + event.target.name); }
For more information on ActionScript 3.0 event handling, see Programming ActionScript 3.0. For more information on ActionScript 3.0 event handling for components, see Handling events on page 23.
A simple application
This section takes you through the steps to create a simple ActionScript 3.0 application using Flash components and the Flash authoring tool. The example is provided both as a FLA file with the ActionScript code included on the Timeline and also as an external ActionScript class file with a FLA file that contains only the components in the library. In general, you will want to develop larger application using external class files so that you can share code between classes and applications and to make your applications easier to maintain. For more information on programming with ActionScript 3.0, see Programming ActionScript 3.0.
The application will be called Greetings. It uses a TextArea to display a greeting that is initially Hello World. It uses a ColorPicker that allows you to change the color of the text. It uses three RadioButtons that allow you to set the size of the text to small, larger or largest. It uses a ComboBox that allows you to select a different greeting from a drop-down list. The application uses components from the Components panel and also creates application elements through
ActionScript code. With that definition in place, you can start building the application.
4 In the Flash Components panel, select a TextArea component and drag it to the Stage. 5 In the Properties window, with the TextArea selected on the Stage, type aTa for the instance name, and enter the
following information:
Enter 230 for the W value (width). Enter 44 for the H value (height). Enter 165 for the X value (horizontal position). Enter 57 for the Y value (vertical position). Enter Hello World! for the text parameter, on the Parameters tab.
6 Drag a ColorPicker component to the Stage, place it to the left of the TextArea and give it an instance name of
largerRb, and largestRb. Enter the following information for them in the Property inspector:
Enter 100 for the W value and 22 for the H value for each of them. Enter 155 for the X value. Enter 120 for the Y value for smallRb, 148 for largerRb, and 175 for largestRb. Enter fontRbGrp for the groupName parameter for each of them. Enter labels for them on the Parameters tab of Small, Larger, Largest.
8 Drag a ComboBox to the Stage and give it an instance name of msgCb. Enter the following information for it in the
Property inspector:
Enter 130 for the W value. Enter 265 for the X value. Enter 120 for the Y value. On the Parameters tab, enter Greetings for the prompt parameter. Double-click the text field for the dataProvider parameter to open the Values dialog box. Click the plus sign and replace the label value with Hello World! Repeat the preceding step to add the label values Have a nice day! and Top of the Morning! Click OK to close the Values dialog box.
9 Save the file. 10 If it is not already open, open the Actions panel by hitting F9 or selecting Actions from the Window menu. Click
Frame 1 on the main Timeline and enter the following code in the Actions panel:
import import import import flash.events.Event; fl.events.ComponentEvent; fl.events.ColorPickerEvent; fl.controls.RadioButtonGroup;
The first three lines import the event classes that the application uses. An event occurs when a user interacts with one of the components. The next five lines register event handlers for the events that the application wants to listen for. A click event occurs for a RadioButton when a user clicks on it. A change event occurs when a user selects a different color in the ColorPicker. A change event occurs on the ComboBox when a user chooses a different greeting from the drop-down list. The fourth line imports the RadioButtonGroup class so that the application can assign an event listener to the group of RadioButtons, rather than assigning the listener to each button individually.
11 Add the following line of code to the Actions panel to create the tf TextFormat object, which the application uses
to change the size and color style properties of the text in the TextArea.
var tf:TextFormat = new TextFormat();
12 Add the following code to create the rbHandler event handling function. This function handles a click event
This function uses a switch statement to examine the target property of the event object to determine which RadioButton triggered the event. The currentTarget property contains the name of the object that triggered the event. Depending on which RadioButton the user clicked, the application changes the size of the text in the TextArea to 14, 18, or 24 points.
13 Add the following code to implement the cpHandler() function, which handles a change to the value in the
ColorPicker:
function cpHandler(event:ColorPickerEvent):void { tf.color = event.target.selectedColor; aTa.setStyle("textFormat", tf); }
This function sets the color property of the tf TextFormat object to the color selected in the ColorPicker and then calls setStyle() to apply it to the text in the aTa TextArea instance.
14 Add the following code to implement the cbHandler() function, which handles a change to the selection in the
ComboBox:
function cbHandler(event:Event):void { aTa.text = event.target.selectedItem.label; }
This function simply replaces the text in the TextArea with the selected text in the ComboBox, event.target.selectedItem.label.
15 Select Control > Test Movie or press Control+Enter to compile the code and test the Greetings application.
The following section shows you how to build the same application with an external ActionScript class and a FLA file that has only the required components in the library. Create the Greetings2 application with an external class file: 1 Select File > New.
2 In the New Document dialog box, select Flash File (ActionScript 3.0), and click OK.
If Flash displays a warning, saying that a definition for the document class could not be found, ignore it. You will define the Greetings2 class in the following steps. This class defines the main functionality for the application.
6 Save the Greetings2.fla file. 7 Select File > New. 8 In the New Document dialog box, select ActionScript File, and click OK.
The script defines an ActionScript 3.0 class, named Greetings2. The script does the following:
It imports classes that we will use in the file. Normally you would add these import statements as you reference
different classes in the code, but for the sake of brevity, this example imports them all in this one step.
It declares variables that represent the different types of component objects that we will add to the code. Another
variable creates the tf TextFormat object.
It defines a constructor function, Greetings2(), for the class. We will add lines to this function, and add other
methods to the class in the following steps.
10 Select File > Save, name the file Greetings2.as, and click the Save button. 11 Add the following lines of code to the Greeting2() function:
createUI(); setUpHandlers(); }
12 Add the following lines of code after the closing brace of the Greeting2() method:
private function createUI() { bldTxtArea(); bldColorPicker(); bldComboBox(); bldRadioButtons(); } private function bldTxtArea() { aTa = new TextArea(); aTa.setSize(230, 44); aTa.text = "Hello World!"; aTa.move(165, 57); addChild(aTa); } private function bldColorPicker() { txtCp = new ColorPicker(); txtCp.move(96, 72); addChild(txtCp); } private function bldComboBox() { msgCb = new ComboBox(); msgCb.width = 130; msgCb.move(265, 120); msgCb.prompt = "Greetings"; msgCb.addItem({data:"Hello.", label:"English"}); msgCb.addItem({data:"Bonjour.", label:"Franais"}); msgCb.addItem({data:"Hola!", label:"Espaol"}); addChild(msgCb); } private function bldRadioButtons() { rbGrp = new RadioButtonGroup("fontRbGrp"); smallRb = new RadioButton(); smallRb.setSize(100, 22);
smallRb.move(155, 120); smallRb.group = rbGrp; //"fontRbGrp"; smallRb.label = "Small"; smallRb.name = "smallRb"; addChild(smallRb); largerRb = new RadioButton(); largerRb.setSize(100, 22); largerRb.move(155, 148); largerRb.group = rbGrp; largerRb.label = "Larger"; largerRb.name = "largerRb"; addChild(largerRb); largestRb = new RadioButton(); largestRb.setSize(100, 22); largestRb.move(155, 175); largestRb.group = rbGrp; largestRb.label = "Largest"; largestRb.name = "largestRb"; addChild(largestRb); }
Instantiate the components used in the application. Set each components size, position, and properties. Add each component to the Stage, using the addChild() method.
13 After the closing brace of the bldRadioButtons() method, add the following code for the setUpHandlers()
method:
private function setUpHandlers():void { rbGrp.addEventListener(MouseEvent.CLICK, rbHandler); txtCp.addEventListener(ColorPickerEvent.CHANGE,cpHandler); msgCb.addEventListener(Event.CHANGE, cbHandler); } private function rbHandler(event:MouseEvent):void { switch(event.target.selection.name) { case "smallRb": tf.size = 14; break; case "largerRb": tf.size = 18; break; case "largestRb": tf.size = 24; break; } aTa.setStyle("textFormat", tf); } private function cpHandler(event:ColorPickerEvent):void { tf.color = event.target.selectedColor; aTa.setStyle("textFormat", tf); } private function cbHandler(event:Event):void { aTa.text = event.target.selectedItem.data; } } }
16
For more information on component skins and customizing components, see Customizing the UI Components on page 95 and Customize the FLVPlayback component on page 149.
To speed up compilation for your applications and to avoid conflicts with your ActionScript 3.0 settings, the Flash CS5 FLA-based UI components also contain a SWC that contains the components already compiled ActionScript code. The ComponentShim SWC is placed on Stage on Frame 2 in every User Interface component to make available the precompiled definitions. To be available for ActionScript, a component must either be on Stage or be in the library with the Export In First Frame option selected in its Linkage properties. To create a component using ActionScript, you also must import the class with an import statement to access it. For information on the import statement, see the ActionScript 3.0 Reference for Flash Professional.
SWC-based Components
SWC-based components have a FLA file and an ActionScript class file, too, but they have been compiled and exported as a SWC. A SWC file is a package of precompiled Flash symbols and ActionScript code that allows you to avoid recompiling symbols and code that will not change. The FLVPlayback and FLVPlaybackCaptioning components are SWC-based components. They have external rather than built-in skins. The FLVPlayback component has a default skin that you can change by selecting one from a collection of predesigned skins, by customizing controls from the UI controls in the Components panel (BackButton, BufferingBar, and so on), or by creating a custom skin. For more information, see Customize the FLVPlayback component on page 149. In Flash, you can convert a movie clip to a compiled clip as follows: 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. The compiled clip behaves just like the movie clip from which it was compiled, but compiled clips appear and publish much faster than ordinary movie clips. Compiled clips cant be edited, but their properties can appear in the Property inspector and the Component inspector. SWC components contain a compiled clip, the components pre-compiled ActionScript definitions, and other files that describe the component. If you create your own component, you can export it as a SWC file to distribute it. Export a SWC file Select the movie clip in the Library panel and right-click (Windows) or Control-click (Macintosh), and then select Export SWC File. Note: The format of a Flash CS4 or later SWC file is compatible with the Flex SWC format so that SWC files can be exchanged between the two products, but not necessarily without modifications. For information on creating SWC-based components, see www.adobe.com/go/learn_fl_creating_components.
For more information about the location of component class files, see Working with component files on page 18.
A components class defines the methods, properties, events, and styles that enable you to interact with it in your application. The ActionScript 3.0 UI components are subclasses of the Sprite and UIComponent classes and inherit properties, methods, and events from them. The Sprite class is the basic display list building block and is similar to a MovieClip but does not have a Timeline. The UIComponent class is the base class for all visual components, both interactive and non-interactive. The inheritance path of each component, as well as its properties, methods, events, and styles are described in the Adobe ActionScript 3.0 Reference for Flash Professional. All ActionScript 3.0 components use the ActionScript 3.0 event handling model. For more information on event handling, see Handling events on page 23 and Programming ActionScript 3.0.
Windows 2000 or Windows XP: C:\Program Files\Adobe\Adobe Flash CS5\language\Configuration\Components Mac OS X: Macintosh HD:Applications:Adobe Flash CS5:Configuration:Components
Within the Components folder, the User Interface (UI) components are in the User Interface.fla file and the FLVPlayback (FLVPlaybackAS3.swc) and FLVPlaybackCaptioning components are in the Video folder. You can also store components in the following user-based locations:
FLVPlayback Macintosh HD:Applications:Adobe Flash CS5:Configuration:Component Source:ActionScript 3.0:FLVPlayback:fl:video FLVPlaybackCaptioning Macintosh HD:Applications:Adobe Flash CS5:Configuration:Component Source:ActionScript 3.0:FLVPlaybackCaptioning:fl:video
The location of the component package folders is relative to the location of the source files for the component type. To reference all of the ActionScript 3.0 source files for all UI components, add the following location to your Classpath for the User Interface packages:
Windows 2000 or Windows XP: C:\Program Files\Adobe\Adobe Flash CS5\language\Configuration\ Mac OS X: Macintosh HD:Applications:Adobe Flash CS5:Configuration
Note: If you must change a component source file, Adobe strongly recommends that you copy the original source file to a different location and add that location to your Classpath. For more information about the location of component source files, see Where component source files are stored on page 18.
list that says Movie Clip. Or click the Parameters tab and enter the name in the box below the word Component. Enter values for any parameters that you want to set.
Its a good idea to add a suffix to the instance name to indicate what kind of component it is; this makes it easier to read your ActionScript code. For example, the instance name licenseSb identifies that a component is a scroll bar that scrolls a license agreement in the licenseTa text area. 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 Click the Parameters tab and enter values for any of the listed parameters.
The following if statement checks to see if the user has selected the check box:
if (aCh.selected == true) { displayImg(redCar); }
The library
When you first add a component to a document, Flash imports it as a movie clip into the Library panel. You can also drag a component from the Components panel directly to the Library panel and then add an instance of it to the Stage. In any case, you must add a component to the library before you can access its class elements. If you add a component to the library and create an instance of it using ActionScript, you must first import its class with the import statement. In the import statement, you must specify both the components package name and its class name. For example, the following statement imports the Button class:
import fl.controls.Button;
When you place a component in the library, Flash also imports a folder of its assets, which contain the skins for its different states. A components skins comprise the collection of symbols that make up its graphical display in the application. A single skin is the graphical representation, or movie clip, that indicates a particular state for the component.
The contents of the Component Assets folder allow you to change the components skins if you wish to do that. For more information, see Customizing the UI Components on page 95. Once a component is in the library, you can add more instances of it to your document by dragging its icon to the Stage from either the Components panel or the Library panel.
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 UIComponent.setSize()) to resize it. The following code resizes an instance of the List component to 200 pixels wide and 300 pixels high:
aList.setSize(200, 300);
A component does not resize automatically to fit its label. If a component instance that has been added to a document is not large enough to display its label, the label text is clipped. You must resize the component to fit its label. For more information about sizing components, see their individual entries in the ActionScript 3.0 Reference for Flash Professional.
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. To turn Live Preview on or off:
Select Control > Enable Live Preview. A check mark next to the option indicates that it is enabled.
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 ActionScript 3.0 Reference for Flash Professional.
Components in Live Preview are not functional. To test functionality, you must use the Control > Test Movie command.
Handling events
Every component broadcasts events when a user interacts with it. When a user clicks a Button, for example, it dispatches a MouseEvent.CLICK event and when a user selects an item in a List, the List dispatches an Event.CHANGE event. An event can also occur when something significant happens to a component such as when content finishes loading for a UILoader instance, generating an Event.COMPLETE event. To handle an event, you write ActionScript code that executes when the event occurs. A components events include the events of any class from which the component inherits. This means that all ActionScript 3.0 User Interface components inherit events from the UIComponent class because it is the base class for the ActionScript 3.0 User Interface components. To see the list of events a component broadcasts, see the Events section of the components class entry in the ActionScript 3.0 Reference for Flash Professional. For a complete explanation of event handling in ActionScript 3.0, see Programming ActionScript 3.0.
All events are broadcast by an instance of a component class. The component instance is the broadcaster. You register an event listener by calling the addEventListener() method for the component instance. For
example, the following line of code adds a listener for the MouseEvent.CLICK event to the Button instance
aButton: aButton.addEventListener(MouseEvent.CLICK, clickHandler);
The second parameter of the addEventListener() method registers the name of the function, clickHandler, to be called when the event occurs. This function is also referred to as a callbackfunction.
The event handler function is passed to an event object that contains information about the event type and the
instance that broadcast the event. For more information, see About the event object on page 23.
The listener remains active until the application terminates or you explicitly remove it using the
removeEventListener() method. For example, the following line of code removes the listener for the MouseEvent.CLICK event on aButton: aButton.removeEventListener(MouseEvent.CLICK, clickHandler);
Description A string indicating the type of the event. A reference to the component instance broadcasting the event.
When an event has additional properties, they are listed in the events class description in the ActionScript 3.0 Reference for Flash Professional. The event object is automatically generated and passed to the event handler function when an event occurs. 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 aButton and display it in the Output panel:
import fl.controls.Button; import flash.events.MouseEvent; var aButton:Button = new Button(); aButton.label = "Submit"; addChild(aButton); aButton.addEventListener(MouseEvent.CLICK, clickHandler); function clickHandler(evtObj:MouseEvent){ trace("The " + evtObj.target.label + " button was clicked"); }
The Stage, which is the top-level container Display objects, which include shapes, MovieClips, and text fields, among others Display object containers, which are special types of display objects that can contain child display objects.
The order of objects in the display list determines their depth in the parent container. An objects depth refers to its position from top to bottom or front to back on the Stage or in its display container. The order of depth is apparent when objects overlap but it exists even when they do not. Every object in the display list has a corresponding depth on the Stage. If you want to change an objects depth by placing it in front of or moving it behind other objects, you need to change its position in the display list. The default order of objects in the display list is the order in which they are placed on the Stage. Position 0 in the display list is the object at the bottom of the depth order.
Note: When you add a component with ActionScript, you must assign a name to its name property if you want to access it by name in the display list. The following example displays the names and positions of three components in the display list. First, drag a NumericStepper, a Button, and a ComboBox to the Stage so that they overlap each other and give them instance names of aNs, aButton, and aCb. Then add the following code to the Actions panel on Frame 1 of the Timeline:
var i:int = 0; while(i < numChildren) { trace(getChildAt(i).name + " is at position: " + i++); }
The NumericStepper should also appear in front of the other components on the screen. Note that numChildren is the number of objects (from 1 to n) in the display list while the first position in the list is 0. So if there are three objects in the list, the index position of the third object is 2. This means that you can reference the last position in the display list, or the top object in terms of display depth, as numChildren - 1.
import fl.controls.Button; var i:int = 0; while(i++ < 3) { makeButton(i); } function removeButton(event:MouseEvent):void { removeChildAt(numChildren -1); } function makeButton(num) { var aButton:Button = new Button(); aButton.name = "Button" + num; aButton.label = aButton.name; aButton.move(200, 200); addChild(aButton); aButton.addEventListener(MouseEvent.CLICK, removeButton); }
For a complete explanation of the display list, see Display programming in Programming ActionScript 3.0.
You can determine which component has focus by calling the getFocus() method and you can determine which component in the tab loop will receive focus next by calling the getNextFocusManagerComponent() method. In the following example, a CheckBox, a RadioButton, and a Button are on the Stage and each component has listeners for MouseEvent.CLICK and FocusEvent.MOUSE_FOCUS_CHANGE events. When the MouseEvent.CLICK event occurs, because the user clicked on the component, the showFocus() function calls the getNextFocusManagerComponent() method to determine which component in the tab loop would receive focus next. It then calls the setFocus() method to give focus to that component. When the FocusEvent.MOUSE_FOCUS_CHANGE event occurs, the fc() function displays the name of the component on which this event occurred. This event is triggered when the user clicks on a component other than the next one in the tab loop.
// This example assumes a CheckBox (aCh), a RadioButton (aRb) and a Button // (aButton) have been placed on the Stage. import fl.managers.FocusManager; import flash.display.InteractiveObject; var fm:FocusManager = new FocusManager(this); aCh.addEventListener(MouseEvent.CLICK, showFocus); aRb.addEventListener(MouseEvent.CLICK, showFocus); aButton.addEventListener(MouseEvent.CLICK, showFocus); aCh.addEventListener(FocusEvent.MOUSE_FOCUS_CHANGE, fc); aRb.addEventListener(FocusEvent.MOUSE_FOCUS_CHANGE, fc); aButton.addEventListener(FocusEvent.MOUSE_FOCUS_CHANGE, fc); function showFocus(event:MouseEvent):void { var nextComponent:InteractiveObject = fm.getNextFocusManagerComponent(); trace("Next component in tab loop is: " + nextComponent.name); fm.setFocus(nextComponent); } function fc(fe:FocusEvent):void { trace("Focus Change: " + fe.target.name); }
To create a Button that receives focus when a user presses Enter (Windows) or Return (Macintosh), set the FocusManager.defaultButton property to the Button instance that you want to be the default Button, as in the following code:
import fl.managers.FocusManager; var fm:FocusManager = new FocusManager(this); fm.defaultButton = okButton;
The FocusManager class 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 3.0 Reference for Flash Professional. To create a custom focus manager, you must create a class that implements the IFocusManager interface. For more information, see IFocusManager in the ActionScript 3.0 Reference for Flash Professional.
The data values that cells hold are called items. An item is an ActionScript object used for storing the units of
information in a List. A List can be thought of as an array with each indexed space of the array being an item. In a List, an item is an object that typically has a label property that is displayed and a data property that is used for storing data. A data provider is a data model of the items in a List. A data provider allows you to populate a Listbased component simply by assigning it to the components dataProvider property.
A cell can hold different types of data that range from text to images, MovieClips, or any class that you can create.
For this reason, a cell must be drawn or rendered in a way that is appropriate for its content. Consequently, Listbased components have a cell renderer to render its cells. In the case of the DataGrid, each column is a DataGridColumn object, which also has a cellRenderer property, so that each column can be rendered appropriately for its content. All List-based components have cellRenderer and dataProvider properties that you can set to load and render the cells of these components. For information on using these properties and working with List-based components, see Work with a DataProvider on page 28 and Work with a CellRenderer on page 36.
Create a DataProvider
For the ComboBox, List, and TileList components you can create a DataProvider using the dataProvider parameter in the authoring environment. The DataGrid component does not have a dataProvider parameter in the Property inspector because it can have several columns and its data provider is consequently more complex. You can also use ActionScript to create a DataProvider for these components, as well as for the DataGrid.
Click the plus sign to add an item to the dataProvider. Click the minus sign to delete an item. Click the up arrow to move a selected item up in the list or click the down arrow to move a selected item down in the list. The following illustration shows a Values dialog box that creates a list of childrens names and their birthdays.
The Array you create consists of pairs of label and value fields. The label fields are label and data and the value fields are the childrens names and their birthdays. The label field identifies the content that appears in the List, which in this case is the names of the children. The resulting ComboBox looks like this:
When you finish adding data, click OK to close the dialog box. The Array in the dataProvider parameter is now populated with the items that you created.
You can access the label and data values that you created by using ActionScript to access the components dataProvider property.
The Array consists of pairs of label and value fields. The label fields are label and data and the value fields are the childrens names and their birthdays. The label field identifies the content that appears in the List, which in this case is the names of the children. The resulting List looks like this:
The value of the data field is available when the user selects an item in the list by clicking it and causing a change event. The following example adds a TextArea (aTa) and an event handler (changeHandler) to the preceding example to display the childs birthday when a user selects a name in the List.
var aList:List = new List(); var aTa:TextArea = new TextArea(); var items:Array = [ {label:"David", data:"1/19/1995"}, {label:"Colleen", data:"4/20/1993"}, {label:"Sharon", data:"9/06/1994"}, {label:"Ronnie", data:"7/6/1993"}, {label:"James", data:"2/15/1994"}, ]; aList.dataProvider = new DataProvider(items); addChild(aList); addChild(aTa); aList.move(150,150); aTa.move(150, 260); aList.addEventListener(Event.CHANGE, changeHandler); function changeHandler(event:Event):void { aTa.text = event.target.selectedItem.data; };
Now when a user selects a childs name in the List, the childs birthday displays in the TextArea as shown in the following illustration. This is accomplished by the changeHandler() function when it sets the text property of the TextArea (aTa.text) to the value of the data field in the selected item (event.target.selectedItem.data). The event.target property is the object that triggered the event, which in this case is the List.
You can include data other than text in a DataProvider. The following example includes MovieClips in a DataProvider that supplies data to a TileList. It builds the DataProvider by calling addItem() to add each item after it creates the MovieClip, a colored box.
import fl.data.DataProvider; import flash.display.DisplayObject; var aBox:MovieClip = new MovieClip(); var i:uint = 0; var colors:Array = new Array(0x00000, 0xFF0000, 0x0000CC, 0x00CC00, 0xFFFF00); var colorNames:Array = new Array("Midnight", "Cranberry", "Sky", "Forest", "July"); var dp:DataProvider = new DataProvider(); for(i=0; i < colors.length; i++) { drawBox(aBox, colors[i]);// draw box w next color in array dp.addItem( {label:colorNames[i], source:aBox} ); } aTl.dataProvider = dp; aTl.columnWidth = 110; aTl.rowHeight = 130; aTl.setSize(280,150); aTl.move(150, 150); aTl.setStyle("contentPadding", 5); function drawBox(box:MovieClip,color:uint):void { box.graphics.beginFill(color, 1.0); box.graphics.drawRect(0, 0, 100, 100); box.graphics.endFill();
You can also use XML data (instead of an array) to populate a DataProvider object. For example, the following code stores data in an XML object named employeesXML, and then passes that object as the value parameter of the DataProvider() constructor function:
import fl.controls.DataGrid; import fl.data.DataProvider; var aDg:DataGrid = new DataGrid(); addChild(aDg); var employeesXML:XML = <employees> <employee Name="Edna" ID="22" /> <employee Name="Stu" ID="23" /> </employees>; var myDP:DataProvider = new DataProvider(employeesXML); aDg.columns = ["Name", "ID"]; aDg.dataProvider = myDP;
You can provide data as attributes of the XML data, as in the previous code, or as properties of the XML data, as in the following code:
var employeesXML:XML = <employees> <employee> <Name>Edna</Name> <ID>22</ID> </employee> <employee> <Name>Stu</Name> <ID>23</ID> </employee> </employees>;
The DataProvider also has a set of methods and properties that allow you to access and manipulate it. You can use the DataProvider API to add, remove, replace, sort, and merge items in a DataProvider.
Manipulate a DataProvider
You can add items to a DataProvider with the addItem() and addItemAt() methods. The following example adds items that a user enters into the text field of an editable ComboBox. It assumes a ComboBox has been dragged onto the Stage and given an instance name of aCb.
import fl.data.DataProvider; import fl.events.ComponentEvent; var items:Array = [ {label:"Roger"}, {label:"Carolyn"}, {label:"Darrell"}, {label:"Rebecca"}, {label:"Natalie"}, {label:"Mitchell"}, ]; aCb.dataProvider = new DataProvider(items); aCb.addEventListener(ComponentEvent.ENTER, newItemHandler); function newItemHandler(event:ComponentEvent):void { var newRow:int = event.target.length + 1; event.target.addItemAt({label:event.target.selectedLabel}, event.target.length); }
You can also replace and remove items in a component through its DataProvider. The following example implements two separate List components, listA and listB, and provides a Button labeled Sync. When a user clicks the Button, the example uses the replaceItemAt() method to replace the items in listB with the items in listA. If listA is longer than listB, the example calls the addItem() method to add the extra items to listB. If listB is longer than listA, the example calls the removeItemAt() method to remove the extra items in ListB.
// Requires the List and Button components to be in the library import import import import fl.controls.List; fl.controls.Button; flash.events.Event; fl.data.DataProvider;
var listA:List = new List(); var listB:List = new List(); var syncButton:Button = new Button(); syncButton.label = "Sync"; var itemsA:Array = [ {label:"David"}, {label:"Colleen"}, {label:"Sharon"}, {label:"Ronnie"}, {label:"James"}, ]; var itemsB:Array = [ {label:"Roger"}, {label:"Carolyn"}, {label:"Darrell"}, {label:"Rebecca"}, {label:"Natalie"}, {label:"Mitchell"}, ]; listA.dataProvider = new DataProvider(itemsA); listB.dataProvider = new DataProvider(itemsB); addChild(listA); addChild(listB); addChild(syncButton); listA.move(100, 100); listB.move(250, 100); syncButton.move(175, 220); syncButton.addEventListener(MouseEvent.CLICK, syncHandler); function syncHandler(event:MouseEvent):void { var i:uint = 0; if(listA.length > listB.length) { //if listA is longer, add items to B while(i < listB.length) { listB.dataProvider.replaceItemAt(listA.dataProvider.getItemAt(i), i);
++i; } while(i < listA.length) { listB.dataProvider.addItem(listA.dataProvider.getItemAt(i++)); } } else if(listA.length == listB.length) { //if listA and listB are equal length while(i < listB.length) { listB.dataProvider.replaceItemAt(listA.dataProvider.getItemAt(i), i); ++i; } } else { //if listB is longer, remove extra items from B while(i < listA.length) { listB.dataProvider.replaceItemAt(listA.dataProvider.getItemAt(i), i); ++i; } while(i < listB.length) { listB.dataProvider.removeItemAt(i++); } } }
You can also merge with and sort a DataProvider using the merge(), sort(), and sortOn() methods. The following example populates two DataGrid instances (aDg and bDg) with partial rosters for two softball teams. It adds a Button with a label of Merge, and when the user clicks it, the event handler (mrgHandler) merges the roster for bDg with the roster for aDg and sorts the resulting DataGrid on the Name column.
import fl.data.DataProvider; import fl.controls.DataGrid; import fl.controls.Button; var aDg:DataGrid = new DataGrid(); var bDg:DataGrid = new DataGrid(); var mrgButton:Button = new Button(); addChild(aDg); addChild(bDg); addChild(mrgButton); bldRosterGrid(aDg); bldRosterGrid(bDg); var aRoster:Array = new Array(); var bRoster:Array = new Array(); aRoster = [ {Name:"Wilma Carter", Bats:"R", Throws:"R", Year:"So", Home: "Redlands, CA"}, {Name:"Sue Pennypacker", Bats:"L", Throws:"R", Year:"Fr", Home: "Athens, GA"}, {Name:"Jill Smithfield", Bats:"R", Throws:"L", Year:"Sr", Home: "Spokane, WA"}, {Name:"Shirley Goth", Bats:"R", Throws:"R", Year:"Sr", Home: "Carson, NV"} ]; bRoster = [ {Name:"Angelina Davis", Bats:"R", Throws:"R", Year:"So", Home: "Odessa, TX"}, {Name:"Maria Santiago", Bats:"L", Throws:"L", Year:"Sr", Home: "Tacoma, WA"}, {Name:"Debbie Ferguson", Bats:"R", Throws:"R", Year: "Jr", Home: "Bend, OR"} ]; aDg.dataProvider = new DataProvider(aRoster); bDg.dataProvider = new DataProvider(bRoster); aDg.move(50,50); aDg.rowCount = aDg.length;
bDg.move(50,200); bDg.rowCount = bDg.length; mrgButton.label = "Merge"; mrgButton.move(200, 315); mrgButton.addEventListener(MouseEvent.CLICK, mrgHandler); function bldRosterGrid(dg:DataGrid){ dg.setSize(400, 300); dg.columns = ["Name", "Bats", "Throws", "Year", "Home"]; dg.columns[0].width = 120; dg.columns[1].width = 50; dg.columns[2].width = 50; dg.columns[3].width = 40; dg.columns[4].width = 120; }; function mrgHandler(event:MouseEvent):void { aDg.dataProvider.merge(bDg.dataProvider); aDg.dataProvider.sortOn("Name"); }
For more information, see the DataProvider class in the ActionScript 3.0 Reference.
Format cells
The CellRenderer class includes a number of styles that let you control the format of the cell. The following styles let you define the skins used for the different states of the cell (disabled, down, over, and up):
disabledSkin and selectedDisabledSkin downSkin and selectedDownSkin overSkin and selectedOverSkin upSkin and selectedUpSkin
You can set these styles by calling the setRendererStyle() method of the List object or by calling the setStyle() method of the CellRenderer object. You can get these styles by calling the getRendererStyle() method of the List object or by calling the getStyle() method of the CellRenderer object. You can also access an object that defines all renderer styles (as named properties of the object) via the rendererStyles property of the List object or the getStyleDefinition() method of the CellRenderer object. You can call the clearRendererStyle() method to reset a style to its default value. To get or set the height of the rows in the list, use the rowHeight property of the List object.
9 Select File > Save. Give the file a name and click the OK button. 10 Select File > New. 11 In the New Document dialog box that is displayed, select ActionScript File and then click the OK button. 12 In the script window, enter the following code to define the CustomCellRenderer class:
package { import fl.controls.listClasses.CellRenderer; import flash.text.TextFormat; import flash.filters.BevelFilter; public class CustomCellRenderer extends CellRenderer { public function CustomCellRenderer() { var format:TextFormat = new TextFormat("Verdana", 12); setStyle("textFormat", format); this.filters = [new BevelFilter()]; } } }
13 Select File > Save. Name the file CustomCellRenderer.as, put it in the same directory as the FLA file, and click the
OK button.
14 Select Control > Test Movie.
Use a class that implements the ICellRenderer interface to define a custom CellRenderer
You can also define a CellRenderer using any class that inherits the DisplayObject class and implements the ICellRenderer interface. For example the following code defines two classes. The ListSample2 class adds a List object to the display list and defines its CellRenderer to use the CustomRenderer class. The CustomRenderer class extends the CheckBox class (which extends the DisplayObject class) and implements the ICellRenderer interface. Note that the CustomRenderer class defines getter and setter methods for the data and listData properties, defined in the ICellRenderer interface. Other properties and methods defined in the ICellRenderer interface (the selected property and the setSize() method) are already defined in the CheckBox class:
1 Select File > New. 2 In the New Document dialog box that is displayed, select Flash File (ActionScript 3.0), and then click OK. 3 Select Window > Components to display the Components panel. 4 In the Components panel, drag a List component to the Stage. 5 If Flash is not displaying the Property inspector, select Window > Properties > Properties. 6 With the List component selected, set the properties in the Property inspector:
9 Select File > Save. Give the file a name and click the OK button. 10 Select File > New. 11 In the New Document dialog box that is displayed, select ActionScript File and then click the OK button. 12 In the script window, enter the following code to define the CustomCellRenderer class:
package { import fl.controls.CheckBox; import fl.controls.listClasses.ICellRenderer; import fl.controls.listClasses.ListData; public class CustomCellRenderer extends CheckBox implements ICellRenderer { private var _listData:ListData; private var _data:Object; public function CustomCellRenderer() { } public function set data(d:Object):void { _data = d; label = d.label; } public function get data():Object { return _data; } public function set listData(ld:ListData):void { _listData = ld; } public function get listData():ListData { return _listData; } } }
13 Select File > Save. Name the file CustomCellRenderer.as, put it in the same directory as the FLA file, and click the
OK button.
14 Select Control > Test Movie.
8 In the Values dialog box that is displayed, click the plus sign twice to add two data elements (with labels set to label0
Text type: Dynamic Text Instance Name: textField W (width): 100 Font size: 24 X: 0 Y: 0
11 With the text field selected, select Modify > Convert To Symbol. 12 In the Convert To Symbol dialog box, make the following settings and then click OK.
Name: MyCellRenderer Type: MovieClip Export for ActionScript: Selected Export in First Frame: Selected Class: MyCellRenderer Base Class: flash.display.MovieClip
If Flash displays an ActionScript Class Warning, click the OK button in the warning box.
13 Delete the instance of the new movie clip symbol from the Stage. 14 Select Frame 1 of Layer 1 in the Timeline, and select Window > Actions. 15 Type the following script in the Actions panel:
myList.setStyle("cellRenderer", MyCellRenderer);
16 Select File > Save. Give the file a name and click the OK button. 17 Select File > New. 18 In the New Document dialog box that is displayed, select ActionScript File and then click the OK button. 19 In the script window, enter the following code to define the MyCellRenderer class:
package { import flash.display.MovieClip; import flash.filters.GlowFilter; import flash.text.TextField; import fl.controls.listClasses.ICellRenderer; import fl.controls.listClasses.ListData; import flash.utils.setInterval; public class MyCellRenderer extends MovieClip implements ICellRenderer { private var _listData:ListData; private var _data:Object; private var _selected:Boolean; private var glowFilter:GlowFilter; public function MyCellRenderer() { glowFilter = new GlowFilter(0xFFFF00); setInterval(toggleFilter, 200); } public function set data(d:Object):void { _data = d; textField.text = d.label; } public function get data():Object { return _data; } public function set listData(ld:ListData):void { _listData = ld; } public function get listData():ListData { return _listData; } public function set selected(s:Boolean):void { _selected = s; } public function get selected():Boolean { return _selected; } public function setSize(width:Number, height:Number):void { } public function setStyle(style:String, value:Object):void { } public function setMouseState(state:String):void{ } private function toggleFilter():void { if (textField.filters.length == 0) { textField.filters = [glowFilter]; } else { textField.filters = []; } } } }
20 Select File > Save. Name the file MyCellRenderer.as, put it in the same directory as the FLA file, and click the OK
button.
21 Select Control > Test Movie.
CellRenderer properties
The data property is an object that contains all properties that are set for the CellRenderer. For example, in the following class, which defines a custom CellRenderer that extends the Checkbox class, note that the setter function for the data property passes the value of data.label to the label property that is inherited from the CheckBox class:
public class CustomRenderer extends CheckBox implements ICellRenderer { private var _listData:ListData; private var _data:Object; public function CustomRenderer() { } public function set data(d:Object):void { _data = d; label = d.label; } public function get data():Object { return _data; } public function set listData(ld:ListData):void { _listData = ld; } public function get listData():ListData { return _listData; } } }
The selected property defines whether or not a cell is selected in the list.
imagePaddingThe padding that separates the edge of the cell from the edge of the image, in pixels selectedSkinThe skin that is used to indicate the selected state textOverlayAlphaThe opacity of the overlay behind the cell label textPaddingThe padding that separates the edge of the cell from the edge of the text, in pixels
The ImageCell class is the default CellRenderer for the TileList class.
The component accessibility classes are in the fl.accessibility package. To make a CheckBox accessible to a screen reader, for example, you would add the following statements to your application:
import fl.accessibility.CheckBoxAccImpl; CheckBoxAccImpl.enableAccessibility();
You enable accessibility for a component only once, regardless of how many instances you create. Note: Enabling accessibility marginally increases file size by including the required classes during compilation. Most components are also navigable through the keyboard. For more information on enabling accessible components and navigating with the keyboard, see the User Interaction sections of Using the UI Components on page 44 and the accessibility classes in the ActionScript 3.0 Reference for Flash Professional.
44
For more information about controlling focus, see the IFocusManager interface and the FocusManager class in the ActionScript 3.0 Reference for Flash Professional and Work with FocusManager on page 26. A live preview of each Button instance reflects changes made to parameters in the Property inspector or Component inspector during authoring. Note: If an icon is larger than the button, it extends beyond the buttons borders. To designate a button as the default push button in an application (the button that receives the click event when a user presses Enter), set FocusManager.defaultButton. For example, the following code sets the default button to be a Button instance called submitButton.
FocusManager.defaultButton = submitButton;
When you add the Button component to an application, you can make it accessible to a screen reader by adding the following lines of ActionScript code:
import fl.accessibility.ButtonAccImpl; ButtonAccImpl.enableAccessibility();
You enable accessibility for a component only once, regardless of how many instances you create.
Property inspector:
Enter the instance name aButton. Enter Show for the label parameter.
3 Add a ColorPicker to the Stage and give it an instance name of aCp. 4 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript code:
aCp.visible = false; aButton.addEventListener(MouseEvent.CLICK, clickHandler); function clickHandler(event:MouseEvent):void { switch(event.currentTarget.label) { case "Show": aCp.visible = true; aButton.label = "Disable"; break; case "Disable": aCp.enabled = false; aButton.label = "Enable"; break; case "Enable": aCp.enabled = true; aButton.label = "Hide"; break; case "Hide": aCp.visible = false; aButton.label = "Show"; break; } }
The second line of code registers the function clickHandler() as the event handler function for the MouseEvent.CLICK event. The event occurs when a user clicks the Button, causing the clickHandler() function to take one of the following actions depending on the Buttons value:
Show makes the ColorPicker visible and changes the Buttons label to Disable.
Disable disables the ColorPicker and changes the Buttons label to Enable. Enable enables the ColorPicker and changes the Buttons label to Hide. Hide makes the ColorPicker invisible and changes the Buttons label to Show.
5 Select Control > Test Movie to run the application.
This adds the component to the library, but doesnt make it visible in the application.
3 Open the Actions panel, select Frame 1 in the main Timeline and enter the following code to create a Button
instance:
import fl.controls.Button; var aButton:Button = new Button(); addChild(aButton); aButton.label = "Click me"; aButton.toggle =true; aButton.move(50, 50);
The move() method positions the button at location 50 (x coordinate), 50 (y coordinate) on the Stage.
4 Now, add the following ActionScript to create an event listener and an event handler function:
aButton.addEventListener(MouseEvent.CLICK, clickHandler); function clickHandler(event:MouseEvent):void { trace("Event type: " + event.type); }
When you click the button, Flash displays the message, Event type: click in the Output panel.
For more information about controlling focus, see Work with FocusManager on page 26 and the FocusManager class in the ActionScript 3.0 Reference for Flash Professional. A live preview of each CheckBox instance reflects changes made to parameters in the Property inspector or Component inspector during authoring. When you add the CheckBox component to an application, you can make it accessible to a screen reader by adding the following lines of ActionScript code:
import fl.accessibility.CheckBoxAccImpl; CheckBoxAccImpl.enableAccessibility();
You enable accessibility for a component only once, regardless of how many instances you have of the component.
Enter homeCh for the instance name. Enter 140 for the width (W) value. Enter Own your home? for the label parameter.
4 Drag two RadioButton components from the Components panel to the Stage and place them below and to the right
of the CheckBox. Enter the following values for them in the Property inspector:
Enter underRb and overRb for the instance names. Enter 120 for the W (width) parameter of both RadioButtons. Enter Under $500,000? for the label parameter of underRb. Enter Over $500,000? for the label parameter of overRb. Enter valueGrp for the groupName parameter for both RadioButtons.
5 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript code:
homeCh.addEventListener(MouseEvent.CLICK, clickHandler); underRb.enabled = false; overRb.enabled = false; function clickHandler(event:MouseEvent):void { underRb.enabled = event.target.selected; overRb.enabled = event.target.selected; }
This code creates an event handler for a CLICK event that enables the underRb and overRb RadioButtons if the homeCh CheckBox is selected, and disables them if homeCh is not selected. For more information, see the MouseEvent class in the ActionScript 3.0 Reference for Flash Professional.
6 Select Control > Test Movie.
The following example duplicates the preceding application but creates the CheckBox and RadioButtons with ActionScript.
documents Library panel. If the Library panel is not open, press Ctrl+L or select Window > Library to open the Library panel. This makes the components available to your application but does not put them on the Stage.
3 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following code to create and position
import fl.controls.CheckBox; import fl.controls.RadioButton; var homeCh:CheckBox = new CheckBox(); var underRb:RadioButton = new RadioButton(); var overRb:RadioButton = new RadioButton(); addChild(homeCh); addChild(underRb); addChild(overRb); underRb.groupName = "valueGrp"; overRb.groupName = "valueGrp"; homeCh.move(200, 100); homeCh.width = 120; homeCh.label = "Own your home?"; underRb.move(220, 130); underRb.enabled = false; underRb.width = 120; underRb.label = "Under $500,000?"; overRb.move(220, 150); overRb.enabled = false; overRb.width = 120; overRb.label = "Over $500,000?";
This code uses the CheckBox() and RadioButton() constructors to create the components and the addChild() method to place them on the Stage. It uses the move() method to position the components on the Stage.
4 Now, add the following ActionScript to create an event listener and an event handler function:
homeCh.addEventListener(MouseEvent.CLICK, clickHandler); function clickHandler(event:MouseEvent):void { underRb.enabled = event.target.selected; overRb.enabled = event.target.selected; }
This code creates an event handler for the CLICK event that enables the underRb and overRb radio buttons if the homeCh CheckBox is selected, and disables them if homeCh is not selected. For more information, see the MouseEvent class in the ActionScript 3.0 Reference for Flash Professional.
5 Select Control > Test Movie.
A user chooses a color by clicking its swatch in the panel or by entering its hexadecimal value in the text field. Once the user selects a color, you can use the ColorPickers selectedColor property to apply the color to text or another object in the application. A ColorPicker instance receives focus if a user moves the pointer over it or tabs to it. When a ColorPickers swatch panel is open, you can use the following keys to control it:
Key Home Up Arrow Down Arrow Right Arrow Left Arrow End Description Moves the selection to the first color in the swatch panel. Moves the selection up one row in the swatch panel. Moves the selection down one row in the swatch panel. Moves the selection in the swatch panel one color to the right. Moves the selection in the swatch panel one color to the left. Moves the selection to the last color in the swatch panel.
In an editable ComboBox, only the button is the hit areanot the text box. For a static ComboBox, the button and the text box constitute the hit area. The hit area responds by opening or closing the drop-down list. When the user makes a selection in the list, either with the mouse or through the keyboard, the label of the selection is copied to the text field at the top of the ComboBox.
When you add the ComboBox component to an application, you can make it accessible to a screen reader by adding the following lines of ActionScript code:
import fl.accessibility.ComboBoxAccImpl; ComboBoxAccImpl.enableAccessibility();
You enable accessibility for a component only once, regardless of how many instances you have of the component.
parameter to true.
3 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following code:
import fl.data.DataProvider; import fl.events.ComponentEvent; var items:Array = [ {label:"screen1", data:"screenData1"}, {label:"screen2", data:"screenData2"}, {label:"screen3", data:"screenData3"}, {label:"screen4", data:"screenData4"}, {label:"screen5", data:"screenData5"}, ]; aCb.dataProvider = new DataProvider(items); aCb.addEventListener(ComponentEvent.ENTER, onAddItem); function onAddItem(event:ComponentEvent):void { var newRow:int = 0; if (event.target.text == "Add") { newRow = event.target.length + 1; event.target.addItemAt({label:"screen" + newRow, data:"screenData" + newRow}, event.target.length); } }
import fl.controls.ComboBox; import fl.data.DataProvider; import flash.net.navigateToURL; var sfUniversities:Array = new Array( {label:"University of California, Berkeley", data:"http://www.berkeley.edu/"}, {label:"University of San Francisco", data:"http://www.usfca.edu/"}, {label:"San Francisco State University", data:"http://www.sfsu.edu/"}, {label:"California State University, East Bay", data:"http://www.csuhayward.edu/"}, {label:"Stanford University", data:"http://www.stanford.edu/"}, {label:"University of Santa Clara", data:"http://www.scu.edu/"}, {label:"San Jose State University", data:"http://www.sjsu.edu/"} ); var aCb:ComboBox = new ComboBox(); aCb.dropdownWidth = 210; aCb.width = 200; aCb.move(150, 50); aCb.prompt = "San Francisco Area Universities"; aCb.dataProvider = new DataProvider(sfUniversities); aCb.addEventListener(Event.CHANGE, changeHandler); addChild(aCb); function changeHandler(event:Event):void { var request:URLRequest = new URLRequest(); request.url = ComboBox(event.target).selectedItem.data; navigateToURL(request); aCb.selectedIndex = -1; }
You can implement and run this example in the Flash authoring environment but you will receive warning messages if you attempt to access the university web sites by clicking items in the ComboBox. To access the fully functional ComboBox on the Internet, access the the following location: http://www.helpexamples.com/peter/bayAreaColleges/bayAreaColleges.html
Up Arrow
Shift+Up/Down Arrow
Shift+Click
Left Arrow
Key PageDown
Description Selects the last row in a page of the DataGrid. A page consists of the number of rows that the DataGrid can display without scrolling. When a cell is editable, the change is committed, and the insertion point is moved to the cell on the same column, next row (up or down, depending on the shift toggle). If the DataGrid is editable, moves focus to the previous/next item until the end of the column is reached and then to the previous/next row until the first or last cell is reached. If the first cell is selected, Shift+Tab moves focus to the preceding control. If the last cell is selected, Tab moves focus to the next control. If the DataGrid is not editable, moves focus to the previous/next control.
Return/Enter/Shift+Enter
Shift+Tab/Tab
You can use the DataGrid component as the foundation for numerous types of data-driven applications. You can easily display a formatted tabular view of data, but you can also use the cell renderer capabilities to build more sophisticated and editable user interface pieces. The following are practical uses for the DataGrid component:
A webmail client Search results pages Spreadsheet applications such as loan calculators and tax form applications
When you design an application with the DataGrid component, it is helpful to understand the design of the List component because the DataGrid class extends the SelectableList class. For more information on the SelectableList class and the List component, see the SelectableList and List classes in the ActionScript 3.0 Reference. When you add a DataGrid component to your application, you can make it accessible to a screen reader by adding the following lines of ActionScript code:
import fl.accessibility.DataGridAccImpl; DataGridAccImpl.enableAccessibility();
You enable accessibility for a component only once, regardless of how many instances the component has. For more information, see Chapter 18, Creating Accessible Content, in Using Flash.
2 Drag the DataGrid component from the Components panel to the Stage. 3 In the Property inspector, enter the instance name aDg. 4 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript code:
import fl.data.DataProvider; bldRosterGrid(aDg); var aRoster:Array = new Array(); aRoster = [ {Name:"Wilma Carter", Bats:"R", Throws:"R", Year:"So", Home: "Redlands, CA"}, {Name:"Sue Pennypacker", Bats:"L", Throws:"R", Year:"Fr", Home: "Athens, GA"}, {Name:"Jill Smithfield", Bats:"R", Throws:"L", Year:"Sr", Home: "Spokane, WA"}, {Name:"Shirley Goth", Bats:"R", Throws:"R", Year:"Sr", Home: "Carson, NV"}, {Name:"Jennifer Dunbar", Bats:"R", Throws:"R", Year:"Fr", Home: "Seaside, CA"}, {Name:"Patty Crawford", Bats:"L", Throws:"L", Year:"Jr", Home: "Whittier, CA"}, {Name:"Angelina Davis", Bats:"R", Throws:"R", Year:"So", Home: "Odessa, TX"}, {Name:"Maria Santiago", Bats:"L", Throws:"L", Year:"Sr", Home: "Tacoma, WA"}, {Name:"Debbie Ferguson", Bats:"R", Throws:"R", Year: "Jr", Home: "Bend, OR"}, {Name:"Karen Bronson", Bats:"R", Throws:"R", Year: "Sr", Home: "Billings, MO"}, {Name:"Sylvia Munson", Bats:"R", Throws:"R", Year: "Jr", Home: "Pasadena, CA"}, {Name:"Carla Gomez", Bats:"R", Throws:"L", Year: "Sr", Home: "Corona, CA"}, {Name:"Betty Kay", Bats:"R", Throws:"R", Year: "Fr", Home: "Palo Alto, CA"}, ]; aDg.dataProvider = new DataProvider(aRoster); aDg.rowCount = aDg.length; function bldRosterGrid(dg:DataGrid){ dg.setSize(400, 300); dg.columns = ["Name", "Bats", "Throws", "Year", "Home"]; dg.columns[0].width = 120; dg.columns[1].width = 50; dg.columns[2].width = 50; dg.columns[3].width = 40; dg.columns[4].width = 120; dg.move(50,50); };
The bldRosterGrid() function sets the size of the DataGrid and sets the order of the columns and their sizes.
5 Select Control > Test Movie.
Specify columns and add sorting for a DataGrid component in an application Notice that you can click any column heading to sort the DataGrids content in descending order by that columns values. The following example uses the addColumn() method to add DataGridColumn instances to a DataGrid. The columns represent player names and their scores. The example also sets the sortOptions property to specify the sort options for each column: Array.CASEINSENSITIVE for the Name column and Array.NUMERIC for the Score column. It sizes the DataGrid appropriately by setting the length to the number of rows and the width to 200.
1 In Flash, select File > New, and then select Flash File (ActionScript 3.0). 2 Drag the DataGrid component from the Components panel to the Stage. 3 In the Property inspector, enter the instance name aDg. 4 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript code:
import fl.controls.dataGridClasses.DataGridColumn; import fl.events.DataGridEvent; import fl.data.DataProvider; // Create columns to enable sorting of data. var nameDGC:DataGridColumn = new DataGridColumn("name"); nameDGC.sortOptions = Array.CASEINSENSITIVE; var scoreDGC:DataGridColumn = new DataGridColumn("score"); scoreDGC.sortOptions = Array.NUMERIC; aDg.addColumn(nameDGC); aDg.addColumn(scoreDGC); var aDP_array:Array = new Array({name:"clark", score:3135}, {name:"Bruce", score:403}, {name:"Peter", score:25}) aDg.dataProvider = new DataProvider(aDP_array); aDg.rowCount = aDg.length; aDg.width = 200;
Create a DataGrid component instance using ActionScript This example creates a DataGrid using ActionScript and populates it with an Array of player names and scores.
1 Create a new Flash (ActionScript 3.0) document. 2 Drag the DataGrid component from the Components panel to the current documents Library panel.
This adds the component to the library but doesnt make it visible in the application.
3 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript code:
import fl.controls.DataGrid; import fl.data.DataProvider; var aDg:DataGrid = new DataGrid(); addChild(aDg); aDg.columns = [ "Name", "Score" ]; aDg.setSize(140, 100); aDg.move(10, 40);
This code creates the DataGrid instance and then sizes and positions the grid.
4 Create an array, add data to the array, and identify the array as the data provider for the DataGrid:
var aDP_array:Array = new Array(); aDP_array.push({Name:"Clark", Score:3135}); aDP_array.push({Name:"Bruce", Score:403}); aDP_array.push({Name:"Peter", Score:25}); aDg.dataProvider = new DataProvider(aDP_array); aDg.rowCount = aDg.length;
Load a DataGrid with an XML file The following example uses the DataGridColumn class to create the DataGrids columns. It populates the DataGrid by passing an XML object as the value parameter of the DataProvider() constructor.
1 Using a text editor create an XML file with the following data and save it as team.xml in the same folder where
<team> <player name="Player A" avg="0.293" /> <player name="Player B" avg="0.214" /> <player name="Player C" avg="0.317" /> </team>
2 Create a new Flash (ActionScript 3.0) document. 3 In the Components panel, double-click the DataGrid component to add it to the Stage. 4 In the Property inspector, enter the instance name aDg. 5 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript code:
import import import import fl.controls.dataGridClasses.DataGridColumn; fl.data.DataProvider; flash.net.*; flash.events.*;
loader.load(request); loader.addEventListener(Event.COMPLETE, loaderCompleteHandler); function loaderCompleteHandler(event:Event):void { var teamXML:XML = new XML(loader.data); var nameCol:DataGridColumn = new DataGridColumn("name"); nameCol.headerText = "Name"; nameCol.width = 120; var avgCol:DataGridColumn = new DataGridColumn("avg"); avgCol.headerText = "Average"; avgCol.width = 60; var myDP:DataProvider = new DataProvider(teamXML); aDg.columns = [nameCol, avgCol]; aDg.width = 200; aDg.dataProvider = myDP; aDg.rowCount = aDg.length; }
A live preview of each Label instance reflects changes made to parameters in the Property inspector or Component inspector during authoring. The label doesnt have a border, so the only way to see its live preview is to set its text parameter.
inspector:
Enter aLabel for the instance name. Enter 80 for the W value. Enter 100 for the X value. Enter 100 for the Y value. Enter Expiration Date for the text parameter.
3 Drag a TextArea component to the Stage and give it the following values in the Property inspector:
Enter aTa for the instance name. Enter 22 for the H value. Enter 200 for the X value. Enter 100 for the Y value.
4 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript code:
var today:Date = new Date(); var expDate:Date = addDays(today, 14); aTa.text = expDate.toDateString(); function addDays(date:Date, days:Number):Date { return addHours(date, days*24); } function addHours(date:Date, hrs:Number):Date { return addMinutes(date, hrs*60); } function addMinutes(date:Date, mins:Number):Date { return addSeconds(date, mins*60); } function addSeconds(date:Date, secs:Number):Date { var mSecs:Number = secs * 1000; var sum:Number = mSecs + date.getTime(); return new Date(sum); }
Note: Note that scroll sizes are in pixels and not rows. Note: The page size used by the Page Up and Page Down keys is one less than the number of items that fit in the display. For example, paging down through a ten-line drop-down list shows items 0-9, 9-18, 18-27, and so on, with one item overlapping per page. For more information about controlling focus, see the IFocusManager interface and the FocusManager class in the ActionScript 3.0 Reference for Flash Professional, and Work with FocusManager on page 26. A live preview of each List instance on the Stage reflects changes made to parameters in the Property inspector or Component inspector during authoring. When you add the List component to an application, you can make it accessible to a screen reader by adding the following lines of ActionScript code:
import fl.accessibility.ListAccImpl; ListAccImpl.enableAccessibility();
You enable accessibility for a component only once, regardless of how many instances the component has. For more information, see Chapter 18, Creating Accessible Content, in Using Flash.
ActionScript property of the same name. For information on the possible values for these parameters, see the List class in the ActionScript 3.0 Reference for Flash Professional. For information on using the dataProvider parameter, see Use the dataProvider parameter on page 28.
Enter the instance name aList. Assign a value of 200 to the W (width).
4 Use the Text tool to create a text field below aList and give it an instance name of aTf. 5 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript code:
import fl.controls.List; import flash.text.TextField; aTf.type = TextFieldType.DYNAMIC; aTf.border = false; // Create these items in the Property inspector when data and label // parameters are available. aList.addItem({label:"1956 Chevy (Cherry Red)", data:35000}); aList.addItem({label:"1966 Mustang (Classic)", data:27000}); aList.addItem({label:"1976 Volvo (Xcllnt Cond)", data:17000}); aList.allowMultipleSelection = true; aList.addEventListener(Event.CHANGE, showData); function showData(event:Event) { aTf.text = "This car is priced at: $" + event.target.selectedItem.data; }
This code uses the addItem() method to populate aList with three items, assigning each one a label value, which appears in the list, and a data value. When you select an item in the List, the event listener calls the showData() function, which displays the data value for the selected item.
6 Select Control > Test Movie to compile and run this application.
Populate a List instance with a data provider This example creates a List of car models and their prices. It uses a data provider to populate the List, however, rather than the addItem() method.
1 Create a new Flash (ActionScript 3.0) document. 2 Drag a List component from the Components panel to the Stage. 3 In the Property inspector, do the following:
Enter the instance name aList. Assign a value of 200 to the W (width).
4 Use the Text tool to create a text field below aList and give it an instance name of aTf. 5 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript code:
import fl.controls.List; import fl.data.DataProvider; import flash.text.TextField; aTf.type = TextFieldType.DYNAMIC; aTf.border = false; var cars:Array = [ {label:"1956 Chevy (Cherry Red)", data:35000}, {label:"1966 Mustang (Classic)", data:27000}, {label:"1976 Volvo (Xcllnt Cond)", data:17000}, ]; aList.dataProvider = new DataProvider(cars); aList.allowMultipleSelection = true; aList.addEventListener(Event.CHANGE, showData); function showData(event:Event) { aTf.text = "This car is priced at: $" + event.target.selectedItem.data; }
6 Select Control > Test Movie to see the List with its items.
Use a List component to control a MovieClip instance The following example creates a List of color names and when you select one, it applies the color to a MovieClip.
1 Create a Flash (ActionScript 3.0) document. 2 Drag the List component from the Components panel to the Stage and give it the following values in the Property
inspector:
Enter aList for the instance name. Enter 60 for the H value. Enter 100 for the X value. Enter 150 for the Y value.
3 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript code:
aList.addItem({label:"Blue", data:0x0000CC}); aList.addItem({label:"Green", data:0x00CC00}); aList.addItem({label:"Yellow", data:0xFFFF00}); aList.addItem({label:"Orange", data:0xFF6600}); aList.addItem({label:"Black", data:0x000000}); var aBox:MovieClip = new MovieClip(); addChild(aBox); aList.addEventListener(Event.CHANGE, changeHandler); function changeHandler(event:Event) { drawBox(aBox, event.target.selectedItem.data); }; function drawBox(box:MovieClip,color:uint):void { box.graphics.beginFill(color, 1.0); box.graphics.drawRect(225, 150, 100, 100); box.graphics.endFill(); }
4 Select Control > Test Movie to run the application. 5 Click colors in the List to see them displayed in a MovieClip.
Create a List component instance using ActionScript: This example creates a simple list using ActionScript, and populates it using the addItem() method.
1 Create a new Flash (ActionScript 3.0) document. 2 Drag the List component from the Components panel to the Library panel. 3 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript code:
import fl.controls.List; var aList:List = new List(); aList.addItem({label:"One", data:1}); aList.addItem({label:"Two", data:2}); aList.addItem({label:"Three", data:3}); aList.addItem({label:"Four", data:4}); aList.addItem({label:"Five", data:5}); aList.setSize(60, 40); aList.move(200,200); addChild(aList); aList.addEventListener(Event.CHANGE, changeHandler); function changeHandler(event:Event):void { trace(event.target.selectedItem.data); }
For more information about controlling focus, see the FocusManager class in the ActionScript 3.0 Reference for Flash Professional and Work with FocusManager on page 26.
This example sets the text property of the label to the value of the NumericStepper. The changeHandler() function updates the labels text property whenever the value in the NumericStepper instance changes.
6 Select Control > Test Movie.
Create a NumericStepper using ActionScript: This example creates three NumericSteppers with ActionScript code, one each for entering the month, day, and year of the users date of birth. It also adds Labels for a prompt and for identifiers for each of the NumericSteppers.
1 Create a new Flash (ActionScript 3.0) document. 2 Drag a Label to the Library panel. 3 Drag a NumericStepper component to the Library panel. 4 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript code:
import fl.controls.Label; import fl.controls.NumericStepper; var var var var dobPrompt:Label = new Label(); moPrompt:Label = new Label(); dayPrompt:Label = new Label(); yrPrompt:Label = new Label();
var moNs:NumericStepper = new NumericStepper(); var dayNs:NumericStepper = new NumericStepper(); var yrNs:NumericStepper = new NumericStepper(); addChild(dobPrompt); addChild(moPrompt); addChild(dayPrompt); addChild(yrPrompt); addChild(moNs); addChild(dayNs); addChild(yrNs); dobPrompt.setSize(65, 22); dobPrompt.text = "Date of birth:"; dobPrompt.move(80, 150); moNs.move(150, 150); moNs.setSize(40, 22); moNs.minimum = 1; moNs.maximum = 12; moNs.stepSize = 1; moNs.value = 1; moPrompt.setSize(25, 22); moPrompt.text = "Mo."; moPrompt.move(195, 150); dayNs.move(225, 150); dayNs.setSize(40, 22); dayNs.minimum = 1; dayNs.maximum = 31; dayNs.stepSize = 1; dayNs.value = 1; dayPrompt.setSize(25, 22); dayPrompt.text = "Day"; dayPrompt.move(270, 150); yrNs.move(300, 150); yrNs.setSize(55, 22); yrNs.minimum = 1900; yrNs.maximum = 2006; yrNs.stepSize = 1; yrNs.value = 1980; yrPrompt.setSize(30, 22); yrPrompt.text = "Year"; yrPrompt.move(360, 150);
In the Property inspector, enter the instance name aPb. In the Parameters section, Enter 200 for the X value. Enter 260 for the Y value.
In the Property inspector, enter loadButton as the instance name. Enter 220 for the X parameter. Enter 290 for the Y parameter. Enter Load Sound for the label parameter.
4 Drag the Label component to the Stage and give it an instance name of progLabel.
Enter 150 for the W value. Enter 200 for the X parameter. Enter 230 for the Y parameter. In the Parameters section, clear the value for the text parameter.
5 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript code, which
Create an application with the ProgressBar component in polled mode The following example sets the ProgressBar to polled mode. In polled mode, progress is determined by listening for progress events on the content that is loading and using its bytesLoaded and bytesTotal properties to calculate progress. This example loads a Sound object, listens for its progress events, and calculates the percent loaded using its bytesLoaded and bytesTotal properties. It displays the percent loaded in both a label and in the Output panel.
1 Create a new Flash (ActionScript 3.0) document. 2 Drag a ProgressBar component from the Components panel to the Stage and enter the following values in the
Property inspector:
Enter aPb for the instance name. Enter 185 for the X value. Enter 225 for the Y value.
3 Drag the Label component to the Stage and enter the following values in the Property inspector:
Enter progLabel for the instance name. Enter 180 for the X value. Enter 180 for the Y value. In the Parameters section, clear the value for the text parameter.
4 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript code, which
creates a Sound object (aSound) and calls loadSound() to load a sound into the Sound object:
import fl.controls.ProgressBarMode; import flash.events.ProgressEvent; import flash.media.Sound; var aSound:Sound = new Sound(); var url:String = "http://www.helpexamples.com/flash/sound/song1.mp3"; var request:URLRequest = new URLRequest(url); aPb.mode = ProgressBarMode.POLLED; aPb.source = aSound; aSound.addEventListener(ProgressEvent.PROGRESS, loadListener); aSound.load(request); function loadListener(event:ProgressEvent) { var percentLoaded:int = event.target.bytesLoaded / event.target.bytesTotal * 100; progLabel.text = "Percent loaded: " + percentLoaded + "%"; trace("Percent loaded: " + percentLoaded + "%"); }
Create an application with the ProgressBar component in manual mode The following example sets the ProgressBar to manual mode. In manual mode, you must set progress manually by calling the setProgress() method and provide it with the current and maximum values to determine the extent of progress. You do not set the source property in manual mode. The example uses a NumericStepper component, with a maximum value of 250, to increment the ProgressBar. When the value in the NumericStepper changes and triggers a CHANGE event, the event handler (nsChangeHander) calls the setProgress() method to advance the ProgressBar. It also displays the percent of progress completed, based on the maximum value.
1 Create a new Flash (ActionScript 3.0) document. 2 Drag the ProgressBar component from the Components panel to the Stage and give it the following values in the
Property inspector:
Enter aPb for the instance name. Enter 180 for the X value. Enter 175 for the Y value.
3 Drag a NumericStepper component to the Stage and enter the following values in the Property inspector:
Enter aNs for the instance name. Enter 220 for the X value. Enter 215 for the Y value. In the Parameters section, enter 250 for the maximum parameter, 0 for the minimum value, 1 for the stepSize
parameter, and 0 for the value parameter.
4 Drag a Label component to the Stage and enter the following values in the Property inspector:
Enter progLabel for the instance name. Enter 150 for the W value. Enter 180 for the X value. Enter 120 for the Y value. In the Parameters tab, clear the value Label for the text parameter.
5 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following code:
import fl.controls.ProgressBarDirection; import fl.controls.ProgressBarMode; import flash.events.Event; aPb.direction = ProgressBarDirection.RIGHT; aPb.mode = ProgressBarMode.MANUAL; aPb.minimum = aNs.minimum; aPb.maximum = aNs.maximum; aPb.indeterminate = false; aNs.addEventListener(Event.CHANGE, nsChangeHandler); function nsChangeHandler(event:Event):void { aPb.value = aNs.value; aPb.setProgress(aPb.value, aPb.maximum); progLabel.text = "Percent of progress = " + int(aPb.percentComplete) + "%"; }
Create a ProgressBar using ActionScript This example creates a ProgressBar using ActionScript. Apart from that, it duplicates the functionality of the preceding example, which creates a ProgressBar in manual mode.
1 Create a new Flash (ActionScript 3.0) document. 2 Drag the ProgressBar component to the Library panel. 3 Drag the NumericStepper component to the Library panel. 4 Drag the Label component to the Library panel. 5 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following code:
import import import import import import fl.controls.ProgressBar; fl.controls.NumericStepper; fl.controls.Label; fl.controls.ProgressBarDirection; fl.controls.ProgressBarMode; flash.events.Event;
var aPb:ProgressBar = new ProgressBar(); var aNs:NumericStepper = new NumericStepper(); var progLabel:Label = new Label(); addChild(aPb); addChild(aNs); addChild(progLabel); aPb.move(180,175); aPb.direction = ProgressBarDirection.RIGHT; aPb.mode = ProgressBarMode.MANUAL; progLabel.setSize(150, 22); progLabel.move(180, 150); progLabel.text = ""; aNs.move(220, 215); aNs.maximum = 250; aNs.minimum = 0; aNs.stepSize = 1; aNs.value = 0; aNs.addEventListener(Event.CHANGE, nsChangeHandler); function nsChangeHandler(event:Event):void { aPb.setProgress(aNs.value, aNs.maximum); progLabel.text = "Percent of progress = " + int(aPb.percentComplete) + "%"; }
6 Select Control > Test Movie to run the application. 7 Click the Up Arrow on the NumericStepper to advance the ProgressBar.
For more information about controlling focus, see the IFocusManager interface and the FocusManager class in the ActionScript 3.0 Reference for Flash Professional and Work with FocusManager on page 26. A live preview of each RadioButton instance on the Stage reflects changes made to parameters in the Property inspector or Component inspector during authoring. However, the mutual exclusion of selection does not display in the live preview. If you set the selected parameter to true for two radio buttons in the same group, they both appear selected even though only the last instance created appears selected at run time. For more information, see RadioButton component parameters on page 74. When you add the RadioButton component to an application, you can make it accessible to a screen reader by adding the following lines of code:
import fl.accessibility.RadioButtonAccImpl; RadioButtonAccImpl.enableAccessibility();
You enable accessibility for a component only once, regardless of how many instances you have of the component. For more information, see Chapter 18, Creating Accessible Content, in Using Flash.
rbGroup.
4 Select the second radio button. In the Property inspector, give it an instance name of noRb and a group name of
rbGroup.
5 Drag a TextArea component from the Components panel to the Stage and give it an instance name of aTa. 6 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript code:
yesRb.label = "Yes"; yesRb.value = "For"; noRb.label = "No"; noRb.value = "Against"; yesRb.move(50, 100); noRb.move(100, 100); aTa.move(50, 30); noRb.addEventListener(MouseEvent.CLICK, clickHandler); yesRb.addEventListener(MouseEvent.CLICK, clickHandler); function clickHandler(event:MouseEvent):void { aTa.text = event.target.value; }
import fl.controls.RadioButton; import fl.controls.RadioButtonGroup; var var var var redRb:RadioButton = new RadioButton(); blueRb:RadioButton = new RadioButton(); greenRb:RadioButton = new RadioButton(); rbGrp:RadioButtonGroup = new RadioButtonGroup("colorGrp");
var aBox:MovieClip = new MovieClip(); drawBox(aBox, 0xCCCCCC); addChild(redRb); addChild(blueRb); addChild(greenRb); addChild(aBox); redRb.label = "Red"; redRb.value = 0xFF0000; blueRb.label = "Blue"; blueRb.value = 0x0000FF; greenRb.label = "Green"; greenRb.value = 0x00FF00; redRb.group = blueRb.group = greenRb.group = rbGrp; redRb.move(100, 260); blueRb.move(150, 260); greenRb.move(200, 260); rbGrp.addEventListener(MouseEvent.CLICK, clickHandler); function clickHandler(event:MouseEvent):void { drawBox(aBox, event.target.selection.value); } function drawBox(box:MovieClip,color:uint):void { box.graphics.beginFill(color, 1.0); box.graphics.drawRect(125, 150, 100, 100); box.graphics.endFill(); }
For more information, see the RadioButton class in the ActionScript 3.0 Reference for Flash Professional.
If you specify a location when loading content to the ScrollPane, you must specify the location (X and Y coordinates) as 0, 0. For example, the following code loads the ScrollPane properly because the box is drawn at location 0, 0:
var box:MovieClip = new MovieClip(); box.graphics.beginFill(0xFF0000, 1); box.graphics.drawRect(0, 0, 150, 300); box.graphics.endFill(); aSp.source = box;//load ScrollPane
For more information, see the ScrollPane class in the ActionScript 3.0 Reference for Flash Professional.
A user can use the mouse to interact with the ScrollPane both on its content and on the vertical and horizontal scroll bars. The user can drag content by using the mouse when the scrollDrag property is set to true. The appearance of a hand pointer on the content indicates that the user can drag the content. Unlike most other controls, actions occur when the mouse button is pressed and continue until it is released. If the content has valid tab stops, you must set scrollDrag to false. Otherwise all mouse hits on the contents will invoke scroll dragging.
var aSp:ScrollPane = new ScrollPane(); var aBox:MovieClip = new MovieClip(); drawBox(aBox, 0xFF0000);//draw a red box aSp.source = aBox; aSp.setSize(150, 200); aSp.move(100, 100); addChild(aSp); function drawBox(box:MovieClip,color:uint):void { box.graphics.beginFill(color, 1); box.graphics.drawRect(0, 0, 150, 300); box.graphics.endFill(); }
Description Decreases the associated value for a vertical slider. Moves focus to the previous object. Moves focus to the next object.
For more information about controlling focus, see the IFocusManager interface and the FocusManager class in the ActionScript 3.0 Reference for Flash Professional and Work with FocusManager on page 26. A live preview of each Slider instance reflects changes made to parameters in the Property inspector or the Component inspector during authoring.
Give it an instance name of valueLabel. Assign the value 0percent to the text parameter.
3 Drag a Slider component from the Components panel and center it below value_lbl.
Give it an instance name of aSlider. Assign it a width (W:) of 200. Assign it a height (H:) of 10. Assign a value of 100 to the maximum parameter. Assign a value of 10 to both the snapInterval and tickInterval parameters.
4 Drag another Label instance from the Library panel and center it below aSlider.
Give it an instance name of promptLabel. Assign it a width (W:) of 250. Assign it a height (H:) of 22. Enter Please indicate your level of satisfaction for the text parameter.
5 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript code:
import fl.controls.Slider; import fl.events.SliderEvent; import fl.controls.Label; aSlider.addEventListener(SliderEvent.CHANGE, changeHandler); function changeHandler(event:SliderEvent):void { valueLabel.text = event.value + "percent"; }
In this example, as you move the thumb of the slider from one interval to another, a listener for the SliderEvent.CHANGE event updates the text property of valueLabel to display the percentage that corresponds to the thumbs position.
Library panel. This adds the components to the library, but doesnt make them visible in the application.
3 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following code to create and position
var sliderLabel:Label = new Label(); sliderLabel.width = 120; sliderLabel.text = "< Fade - Brighten >"; sliderLabel.move(170, 350); var aSlider:Slider = new Slider(); aSlider.width = 200; aSlider.snapInterval = 10; aSlider.tickInterval = 10; aSlider.maximum = 100; aSlider.value = 100; aSlider.move(120, 330); var aLoader:UILoader = new UILoader(); aLoader.source = "http://www.flash-mx.com/images/image1.jpg"; aLoader.scaleContent = false; addChild(sliderLabel); addChild(aSlider); addChild(aLoader); aLoader.addEventListener(Event.COMPLETE, completeHandler); function completeHandler(event:Event) { trace("Number of bytes loaded: " + aLoader.bytesLoaded); } aSlider.addEventListener(SliderEvent.CHANGE, changeHandler); function changeHandler(event:SliderEvent):void { aLoader.alpha = event.value * .01; }
4 Select Control > Test Movie to run the application. 5 Move the Sliders thumb to the left to fade the image and to the right to brighten it.
You can use a TextArea component wherever you need a multiline text field. For example, you could use a TextArea component as a comment field in a form. You could set up a listener that checks whether the field is empty when a user tabs out of the field. That listener could display an error message indicating that a comment must be entered in the field. If you need a single-line text field, use the TextInput component. You can set the textFormat style using the setStyle() method to change the style of text that appears in a TextArea instance. You can also format a TextArea component with HTML using the htmlText property in ActionScript, and you can set the displayAsPassword property to true to mask text with asterisks. If you set the condenseWhite property to true, Flash removes extra white space in new text that is due to spaces, line breaks, and so on. It has no effect on text that is already in the control.
For more information about controlling focus, see the FocusManager class in the ActionScript 3.0 Reference for Flash Professional and Work with FocusManager on page 26.
it an instance name of bTa. Leave its parameters set to the default settings.
4 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript code:
import flash.events.FocusEvent; aTa.restrict = "a-z,'\" \""; aTa.addEventListener(Event.CHANGE,changeHandler); aTa.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, k_m_fHandler); aTa.addEventListener(FocusEvent.MOUSE_FOCUS_CHANGE, k_m_fHandler); function changeHandler(ch_evt:Event):void { bTa.text = aTa.text; } function k_m_fHandler(kmf_event:FocusEvent):void { kmf_event.preventDefault(); }
This example restricts the characters you can enter into the aTa text area to lowercase characters, the comma, the apostrophe, and spaces. It also sets up event handlers for the change, KEY_FOCUS_CHANGE, and MOUSE_FOCUS_CHANGE events on the aTa text area. The changeHandler() function causes the text that you enter in the aTa text area to automatically appear in the bTa text area by assigning aTa.text to bTa.text on each change event. The k_m_fHandler() function for the KEY_FOCUS_CHANGE and MOUSE_FOCUS_CHANGE events prevents you from pressing the Tab key to move to the next field without entering any text. It does this by preventing the default behavior.
5 Select Control > Test Movie.
If you press the Tab key to move focus to the second text area without entering any text, you should see an error message and focus should return to the first text area. As you enter text in the first text area, you will see it duplicated in the second text area.
import fl.controls.TextArea; var aTa:TextArea = new TextArea(); aTa.move(100,100); aTa.setSize(200, 200); aTa.condenseWhite = true; aTa.htmlText = '<b>Lorem ipsum dolor</b> sit amet, consectetuer adipiscing elit. <u>Vivamus quis nisl vel tortor nonummy vulputate.</u> Quisque sit amet eros sed purus euismod tempor. Morbi tempor. <font color="#FF0000">Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos.</font> Curabitur diam. Suspendisse at purus in ipsum volutpat viverra. Nulla pellentesque libero id libero.'; addChild(aTa);
This example uses the htmlText property to apply HTML bold and underline attributes to a block of text and display it in the a_ta text area. The example also sets the condenseWhite property to true to condense the white space within the text block. The setSize() method sets the text areas height and width, and the move() method sets its position. The addChild() method adds the TextArea instance to the Stage.
4 Select Control > Test Movie.
For more information about controlling focus, see the FocusManager class in the ActionScript 3.0 Reference for Flash Professional and Work with FocusManager on page 26. A live preview of each TextInput instance reflects changes made to parameters in the Property inspector or Component inspector during authoring. Text is not selectable in the live preview, and you cannot enter text in the component instance on the Stage.
When you add the TextInput component to an application, you can use the Accessibility panel to make it accessible to screen readers.
inspector:
Enter the instance name pwdLabel. Enter a value for W of 100. Enter a value for X of 50. Enter a value for Y of 150. In the Parameters section, enter a value of Password: for the text parameter.
3 Drag a second Label component from the Components panel to the Stage and give it the following values:
Enter the instance name confirmLabel. Enter a value for W of 100. Enter a value for X of 50. Enter a value for Y of 200. In the Parameters section, enter a value of ConfirmPassword: for the text parameter.
4 Drag a TextInput component from the Components panel to the Stage and give it the following values:
Enter the instance name pwdTi. Enter a value for W of 150. Enter a value for X of 190. Enter a value for Y of 150. In the Parameters section, double-click the value for the displayAsPassword parameter and select true. This
causes the value entered in the text field to be masked with asterisks.
5 Drag a second TextInput component from the Components panel to the Stage and give it the following values:
Enter a value for W of 150. Enter a value for X of 190. Enter a value for Y of 200. In the Parameters section, double-click the value for the displayAsPassword parameter and select true. This
causes the value entered in the text field to be masked with asterisks.
6 Open the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript code:
function tiListener(evt_obj:Event){ if(confirmTi.text != pwdTi.text || confirmTi.length < 8) { trace("Password is incorrect. Please reenter it."); } else { trace("Your password is: " + confirmTi.text); } } confirmTi.addEventListener("enter", tiListener);
This code sets up an enter event handler on the TextInput instance called confirmTi. If the two passwords dont match or the user types fewer than eight characters, the example displays the message: Password is incorrect. Please reenter it. If the passwords are eight characters or more and they match, the example displays the value entered in the Output panel.
7 Select Control > Test Movie.
import fl.controls.Label; import fl.controls.TextInput; var nameLabel:Label = new Label(); var nameTi:TextInput = new TextInput(); var tf:TextFormat = new TextFormat(); addChild(nameLabel); addChild(nameTi); nameTi.restrict = "A-Z .a-z"; tf.font = "Georgia"; tf.color = 0x0000CC; tf.size = 16; nameLabel.text = "Name: " ; nameLabel.setSize(50, 25); nameLabel.move(100,100); nameLabel.setStyle("textFormat", tf); nameTi.move(160, 100); nameTi.setSize(200, 25); nameTi.setStyle("textFormat", tf);
Description Allow you to move up and down through a column. If the allowMultipleSelection property is true, you can use these keys in combination with the Shift key to select multiple cells. Allow you to move to the left or right in a row. If the allowMultipleSelection property is true, you can use these keys in combination with the Shift key to select multiple cells. Selects the first cell in a TileList. If the allowMultipleSelection property is true, holding Shift and pressing Home will select all the cells from your current selection to the first cell. Selects the last cell in a TileList. If the allowMultipleSelection property is true, holding Shift and pressing End will select all the cells from your current selection to the last cell. If the allowMultipleSelection property is set to true, allows you to select multiple cells, in no specific order.
Home
End
Ctrl
When you add the TileList component to an application, you can make it accessible to a screen reader by adding the following lines of ActionScript code:.
import fl.accessibility.TileListAccImpl; TileListAccImpl.enableAccessibility();
You enable accessibility for a component only once, regardless of how many instances the component has. For more information, see Chapter 18, Creating Accessible Content, in Using Flash.
import fl.data.DataProvider; import flash.display.DisplayObject; var aBoxes:Array = new Array(); var i:uint = 0; var colors:Array = new Array(0x00000, 0xFF0000, 0x0000CC, 0x00CC00, 0xFFFF00); var colorNames:Array = new Array("Midnight", "Cranberry", "Sky", "Forest", "July"); var dp:DataProvider = new DataProvider(); for(i=0; i < colors.length; i++) { aBoxes[i] = new MovieClip(); drawBox(aBoxes[i], colors[i]);// draw box w next color in array dp.addItem( {label:colorNames[i], source:aBoxes[i]} ); } aTl.dataProvider = dp; aTl.columnWidth = 110; aTl.rowHeight = 130; aTl.setSize(280,150); aTl.move(150, 150); aTl.setStyle("contentPadding", 5); function drawBox(box:MovieClip,color:uint):void { box.graphics.beginFill(color, 1.0); box.graphics.drawRect(0, 0, 100, 100); box.graphics.endFill(); }
import import import import import import var var var var var
aCp:ColorPicker = new ColorPicker(); aCb:ComboBox = new ComboBox(); aNs:NumericStepper = new NumericStepper(); aCh:CheckBox = new CheckBox(); aTl:TileList = new TileList();
var dp:Array = [ {label:"ColorPicker", source:aCp}, {label:"ComboBox", source:aCb}, {label:"NumericStepper", source:aNs}, {label:"CheckBox", source:aCh}, ]; aTl.dataProvider = new DataProvider(dp); aTl.columnWidth = 110; aTl.rowHeight = 100; aTl.setSize(280,130); aTl.move(150, 150); aTl.setStyle("contentPadding", 5); aTl.sortItemsOn("label"); addChild(aTl);
If the length of the scroll bar is smaller than the combined size of its scroll arrows, it does not display correctly. One of the arrow buttons becomes hidden behind the other. Flash does not provide error checking for this. In this case it is a good idea to hide the scroll bar with ActionScript. If the scroll bar is sized so that there is not enough room for the scroll box (thumb), Flash makes the scroll box invisible. The UIScrollBar component functions like any other scroll bar. It contains arrow buttons at either end and a scroll track and scroll box (thumb) in between. It can be attached to any edge of a text field and used both vertically and horizontally. For information on the TextField, see the TextField class in the ActionScript 3.0 Reference for Flash Professional.
Note: Make sure that the text field on the Stage is small enough that you need to scroll it to see all the text. If it isnt, the scroll bar does not appear or may appear simply as two lines with no thumb grip (the part you drag to scroll the content).
5 Verify that object snapping is turned on (View > Snapping > Snap To Objects). 6 Drag a UIScrollBar instance from the Components panel onto the text input field near the side you want to attach
it to. The component must overlap with the text field when you release the mouse in order for it to be properly bound to the field. Give it an instance name of mySb. The scrollTargetName property of the component is automatically populated with the text field instance name in the Property and Component inspectors. If it does not appear on the Parameters tab, you may not have overlapped the UIScrollBar instance enough.
95
Note: The default appearance of ActionScript 3.0 components could be considered a theme (Aeon Halo), but these skins are built into the components. The ActionScript 3.0 components do not support the external theme files that ActionScript 2.0 components did.
Setting styles
A components styles generally specify values for its skins, icons, text formatting, and padding when Flash draws the component in its various states. For example, Flash draws a Button with a different skin to show its down state, which occurs when you click the mouse button on it, than it does to show its up or normal state. It also uses a different skin when its in a disabled state, which is caused by setting the enabled property to false. You can set styles for components at the document, class, and instance levels. In addition, some style properties can be inherited from a parent component. For example, the List component inherits ScrollBar styles by inheriting from BaseScrollPane. You can set styles to customize a component in the following ways:
Set styles on a component instance. You can change color and text properties for 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.
Set styles for all components of a given type in a document. If you want to apply a consistent look to all components
of a given type, for example to all CheckBoxes or all Buttons in a document, you can set styles at the component level. The values of style properties set on containers are inherited by contained components. Flash does not display changes made to style properties when you view components on the Stage using the Live Preview feature.
1 Flash looks for a style property on the component instance. 2 If the style is one of the inheriting styles, Flash looks through the parent hierarchy for an inherited value. 3 Flash looks for the style on the component. 4 Flash looks for a global setting on StyleManager. 5 If the property is still not defined, the property has the value undefined.
Notice that the getStyle() method returns the type Object because it can return multiple styles having different data types. For example, the following code sets the font style for a TextArea instance (aTa) and then retrieves it using the getStyle() method. The example casts the returned value to a TextFormat object to assign it to a TextFormat variable. Without the cast, the compiler would issue an error for attempting to coerce an Object variable to a TextFormat variable.
import flash.text.TextFormat; var tf:TextFormat = new TextFormat(); tf.font = "Georgia"; aTa.setStyle("textFormat",tf); aTa.text = "Hello World!"; var aStyle:TextFormat = aTa.getStyle("textFormat") as TextFormat; trace(aStyle.font);
The following illustration shows the effect of these settings on a button having a Submit label:
Style properties set on a component instance through setStyle() have the highest priority and override all other style settings. However, the more properties you set using setStyle() on a single component instance, the slower the component will render at run time.
All Buttons that you subsequently add to the Stage will have red labels.
following code in Frame 1 of the Timeline to set the color of text to red for all components:
import fl.managers.StyleManager; var tf:TextFormat = new TextFormat(); tf.color = 0xFF0000; StyleManager.setStyle("textFormat", tf);
4 Add the following code to the Actions panel to populate the List with text.
aList.addItem({label:"1956 Chevy (Cherry Red)", data:35000}); aList.addItem({label:"1966 Mustang (Classic)", data:27000}); aList.addItem({label:"1976 Volvo (Xcllnt Cond)", data:17000}); aList.allowMultipleSelection = true;
5 Select Control > Test Movie or press Ctrl+Enter to compile the code and test your content. The text in both the
About Skins
A components appearance is made up of graphical elements such as an outline, a fill color, icons, and even other components. A ComboBox, for example, contains a List component and a List component contains a ScrollBar. Together the graphical elements make up the appearance for the ComboBox. A components appearance changes, however, based on its current state. For example, a CheckBox, without its label, looks something like this when it appears in your application:
If you click the mouse button and hold it down on the CheckBox, its appearance changes to this:
And when you release the mouse button, the CheckBox reverts to its original appearance but now has a check mark to show that it has been selected.
Collectively, the icons that represent the component in its various states are called its skins. You can change a components appearance in any or all of its states by editing its skins in Flash, just as you would any other Flash symbol. You can access a components skins in two ways. The easiest way is to drag the component to the Stage and doubleclick it. This opens a palette of the components skins, which looks like this for a CheckBox.
A CheckBoxs skins
You can also access a components skins individually from the Library panel. When you drag a component to the Stage, you also copy it to the library along with a folder of its assets and any other components that it contains. For example, if you drag a ComboBox to the Stage, the Library panel will also contain the List, ScrollBar, and TextInput components, which are built into the ComboBox, along with a folder of skins for each of these components and a Shared Assets folder that contains elements that these components share. You can edit the skins for any of these components by opening its skins folder (ComboBoxSkins, ListSkins, ScrollBarSkins, or TextInputSkins) and double-clicking the icon for the skin that you want to edit. Double-clicking ComboBox_downSkin, for example, opens the skin in symbol editing mode, as shown in the following illustration:
The ComboBox_downSkin
Create a new skin for all instances Create new skins for some instances
Select the skin in the components Assets folder in the Library panel. Duplicate the skin and assign it a unique class name. Edit the skin to give it the appearance you want. Call the setStyle() method for the component instance to assign the new skin to the skin style.
The following procedure creates a new selectedDownSkin for one of two Button instances.
1 Create a new Flash file (ActionScript 3.0) document. 2 Drag two Buttons from the Components panel onto the Stage and give them instance names of aButton and
bButton.
3 Open the Library panel and then the Component Assets and ButtonSkins folders within it. 4 Click the selectedDownSkin skin to select it. 5 Right-click to open the context menu and select Duplicate. 6 In the Duplicate Symbol dialog box, give the new skin a unique name, for example Button_mySelectedDownSkin.
open the context menu. Select Linkage to open the Linkage Properties dialog box.
8 Click the Export For ActionScript check box. Leave the Export In First Frame check box selected and ensure that
the class name is unique. Click OK, and then click OK again in response to the warning that says a class definition could not be found and one will be created.
9 Double-click the Button_mySelectedDownSkin skin in the Library panel to open it in symbol-editing mode. 10 Click the blue fill in the center of the skin until the color appears in the Fill color picker in the Property inspector.
Click the color picker and select color #00CC00 for the skin fill.
11 Click the Back button at the left side of the edit bar above the Stage to return to document-editing mode. 12 In the Property inspector, click the Parameters tab for each button and set the toggle parameter to true. 13 Add the following code to the Actions panel on Frame 1 of the Timeline:
bButton.setStyle("selectedDownSkin", Button_mySelectedDownSkin); bButton.setStyle("downSkin", Button_mySelectedDownSkin);
14 Select Control > Text Movie. 15 Click each button. Note that the down skin (selected and unselected) for the bButton object uses the new skin
symbol.
tab of the Property inspector, give them labels of Button A and Button B.
3 Add the following code to the Actions panel on Frame 1 of the Timeline:
bBtn.emphasized = true; aBtn.emphasized = true; bBtn.addEventListener(MouseEvent.CLICK, Btn_handler); function Btn_handler(evt:MouseEvent):void { bBtn.setStyle("emphasizedSkin", "Button_selectedOverSkin"); }
4 Select Control > Test Movie. 5 Click one of the buttons to see the effect of the emphasizedSkin style on each button.
Button skins
If a button is enabled, it displays its over state when the pointer moves over it. The button receives input focus and displays its down state when its pressed. The button returns to its over state when the mouse is released. If the pointer moves off the button while the mouse is pressed, the button returns to its original state. If the toggle parameter is set to true, the pressed state is shown with the selectedDownSkin, the up state with the selectedUpSkin, and the over state with the selectedOverSkin. If a Button is disabled, it displays its disabled state, regardless of user interaction. To edit one of the skins, double-click it to open it in symbol-editing mode, as shown in the following illustration:
At this point you can use the Flash authoring tools to edit the skin to your liking. The following procedure changes the color of the Buttons selected_over skin.
1 Create new Flash file (ActionScript 3.0). 2 Drag a Button from the Components panel to the Stage. In the Parameters tab, set the toggle parameter to true. 3 Double-click the Button to open the palette of its skins. 4 Double-click the selected_over skin to open it in symbol-editing mode. 5 Set the zoom control to 400% to enlarge the icon for editing. 6 Double-click the background until its color appears in the Fill color picker in the Property inspector. 7 Select color #CC0099 in the Fill color picker to apply it to the background of the selected_over skin. 8 Click the Back button at the left side of the edit bar above the Stage to return to document-editing mode. 9 Select Control > Test Movie. 10 Click the button to put it in the selected state.
When you move the mouse pointer over the Button, the selected_over state should appear as it does in the following illustration.
For more information, see Setting styles on page 95. For information on setting style properties to change the components icons and skins, see Create a new skin on page 99 and Use skins with the CheckBox on page 103.
CheckBox skins
This example changes the outline color and background color of the component in its up and selectedUp states. You would follow similar steps to change the skins for other states.
1 Create a new Flash file (ActionScript 3.0) document. 2 Drag the CheckBox component to the Stage, which also places it in the library with a folder of its assets. 3 Double-click the CheckBox component on the Stage to open its panel of skin icons. 4 Double-click the selected_up icon to open it in symbol-editing mode. 5 Set the zoom control to 800% to enlarge the icon for editing. 6 Click the border of the CheckBox to select it. Use the Fill color picker in the Property inspector to select color
background to #00CCFF.
8 Repeat steps 4 to 8 for the CheckBox up skin. 9 Select Control > Test Movie.
4 Select Control > Test Movie. 5 Click the ColorPicker to open it and see how these settings have altered its appearance.
ColorPicker skins
You can change the color of the Background skin to change the color of the palette background.
1 Create a new Flash file (ActionScript 3.0) document. 2 Drag the ColorPicker component to the Stage. 3 Double-click it to open its palette of skins. 4 Double-click the Background skin until it is selected and the Fill color picker appears in the Property inspector. 5 Select color #999999 using the Fill color picker to apply it to the Background skin. 6 Click the Back button at the left side of the edit bar above the Stage to return to document-editing mode. 7 Select Control > Test Movie.
When you click on the ColorPicker, the background of the palette should be gray as shown in the following illustration.
import fl.data.DataProvider; aCb.setSize(150, 35); aCb.setStyle("textPadding", 10); aCb.setStyle("buttonWidth", 10); aCb.editable = true; var items:Array = [ {label:"San Francisco", data:"601 Townsend St."}, {label:"San Jose", data:"345 Park Ave."}, {label:"San Diego", data:"10590 West Ocean Air Drive, Suite 100"}, {label:"Santa Rosa", data:"2235 Mercury Way, Suite 105"}, {label:"San Luis Obispo", data:"3220 South Higuera Street, Suite 311"} ]; aCb.dataProvider = new DataProvider(items);
Notice that the area of the button that you can click to open the drop-down list is only a narrow area on the right side. Notice also that the text is centered vertically in the text field. You can try running the example without the two setStyle() statements to see their effect.
ComboBox skins
You can change the color of the Up skin to change the color of the component in its inactive state on the Stage.
1 Create a new Flash file (ActionScript 3.0) document.
2 Drag the ComboBox component to the Stage. 3 Double-click it to open its palette of skins. 4 Double-click the Up skin until it is selected and open for editing. 5 Set the zoom control to 400%. 6 Click the center area of the skin until its color appears in the Fill color picker in the Property inspector. 7 Select color #33FF99 using the Fill color picker to apply it to the Up skin. 8 Click the Back button at the left side of the edit bar above the Stage to return to document-editing mode. 9 Select Control > Test Movie.
The ComboBox should appear on the Stage as shown in the following illustration.
string of text in the third column. At the end, it sets the columns cellRenderer property to the name of a cell renderer that renders a multiline cell.
/* This is a simple cell renderer example.It invokes the MultiLineCell cell renderer to display a multiple line text field in one of a DataGrid's columns. */ import import import import fl.controls.DataGrid; fl.controls.dataGridClasses.DataGridColumn; fl.data.DataProvider; fl.controls.ScrollPolicy;
// Create a new DataGrid component instance. var aDg:DataGrid = new DataGrid(); var aLongString:String = "An example of a cell renderer class that displays a multiple line TextField" var myDP:Array = new Array(); myDP = [{firstName:"Winston", lastName:"Elstad", note:aLongString, item:100}, {firstName:"Ric", lastName:"Dietrich", note:aLongString, item:101}, {firstName:"Ewing", lastName:"Canepa", note:aLongString, item:102}, {firstName:"Kevin", lastName:"Wade", note:aLongString, item:103}, {firstName:"Kimberly", lastName:"Dietrich", note:aLongString, item:104}, {firstName:"AJ", lastName:"Bilow", note:aLongString, item:105}, {firstName:"Chuck", lastName:"Yushan", note:aLongString, item:106}, {firstName:"John", lastName:"Roo", note:aLongString, item:107}, ]; // Assign the data provider to the DataGrid to populate it. // Note: This has to be done before applying the cellRenderers. aDg.dataProvider = new DataProvider(myDP); /* Set some basic grid properties. Note: The data grid's row height should reflect the number of lines you expect to show in the multiline cell. The cell renderer wil size to the row height. About 40 for 2 lines or 60 for 3 lines.*/ aDg.columns = ["firstName", "lastName", "note", "item"]; aDg.setSize(430,190); aDg.move(40,40); aDg.rowHeight = 40;// Allows for 2 lines of text at default text size. aDg.columns[0].width = 70; aDg.columns[1].width = 70; aDg.columns[2].width = 230; aDg.columns[3].width = 60; aDg.resizableColumns = true; aDg.verticalScrollPolicy = ScrollPolicy.AUTO; addChild(aDg); // Assign cellRenderers. var col3:DataGridColumn = new DataGridColumn(); col3 = aDg.getColumnAt(2); col3.cellRenderer = MultiLineCell;
4 Save the FLA file as MultiLineGrid.fla. 5 Create a new ActionScript file. 6 Copy the following ActionScript code into the Script window:
package {
import fl.controls.listClasses.CellRenderer; public class MultiLineCell extends CellRenderer { public function MultiLineCell() { textField.wordWrap = true; textField.autoSize = "left"; } override protected function drawLayout():void { textField.width = this.width; super.drawLayout(); } } }
7 Save the ActionScript file as MultiLineCell.as in the same folder where you saved the MultiLineGrid.fla. 8 Return to the MultiLineGrid.fla application and select Control > Test Movie.
import fl.data.DataProvider; import fl.controls.dataGridClasses.DataGridColumn; var myDP:Array = new Array(); myDP = [{FirstName:"Winston", LastName:"Elstad"}, {FirstName:"Ric", LastName:"Dietrich"}, {FirstName:"Ewing", LastName:"Canepa"}, {FirstName:"Kevin", LastName:"Wade"}, {FirstName:"Kimberly", LastName:"Dietrich"}, {FirstName:"AJ", LastName:"Bilow"}, {FirstName:"Chuck", LastName:"Yushan"}, {FirstName:"John", LastName:"Roo"}, ]; // Assign the data provider to the DataGrid to populate it. // Note: This has to be done before applying the cellRenderers. aDg.dataProvider = new DataProvider(myDP); aDg.setSize(160,190); aDg.move(40,40); aDg.columns[0].width = 80; aDg.columns[1].width = 80; var tf:TextFormat = new TextFormat(); tf.size = 14; tf.color = 0xff0000; tf.italic = true; tf.font = "Arial" aDg.setStyle("headerTextFormat", tf);
DataGrid skins
The CellRenderer skin is the skin used for the body cells of the DataGrid, while the HeaderRenderer skin is used for the header row. The following procedure changes the background color of the header row but you could use the same process to change the background color of the DataGrids body cells by editing the CellRenderer skin.
1 Create a new Flash document (ActionScript 3.0). 2 Drag the DataGrid component to the Stage and give it an instance name of aDg. 3 Double-click the component to open its palette of skins. 4 Set the zoom control to 400% to enlarge the icons for editing. 5 Double-click the HeaderRenderer skin to open the palette of HeaderRenderer skins. 6 Double-click the Up_Skin to open it in symbol-editing mode and click its background until it is selected and the
import fl.data.DataProvider; bldRosterGrid(aDg); var aRoster:Array = new Array(); aRoster = [ {Name:"Wilma Carter",Home: "Redlands, CA"}, {Name:"Sue Pennypacker",Home: "Athens, GA"}, {Name:"Jill Smithfield",Home: "Spokane, WA"}, {Name:"Shirley Goth", Home: "Carson, NV"}, {Name:"Jennifer Dunbar",Home: "Seaside, CA"} ]; aDg.dataProvider = new DataProvider(aRoster); function bldRosterGrid(dg:DataGrid){ dg.setSize(400, 130); dg.columns = ["Name", "Home"]; dg.move(50,50); dg.columns[0].width = 120; dg.columns[1].width = 120; };
The DataGrid should appear as it does in the following illustration with the background of the header row in green.
Color me red
3 Select Frame 1 in the main Timeline, open the Actions panel, and enter the following code:
/* Create a new TextFormat object, which allows you to set multiple text properties at a time. */ var tf:TextFormat = new TextFormat(); tf.color = 0xFF0000; /* Apply this specific text format (red text) to the Label instance. */ a_label.setStyle("textFormat", tf);
For more information about Label styles, see the Label class in the ActionScript 3.0 Reference for Flash Professional.
List skins
For more information about skinning the ScrollBar, see Customize the UIScrollBar component on page 128. For information on skinning the Focus Rect skin, see Customize the TextArea component on page 123 Note: Changing the ScrollBar skin in one component will change it for all other components that use the ScrollBar. Double-click the Cell Renderer skin to open a second palette of skins for the different states of a List cell.
You can change the appearance of the Lists cells by editing these skins. The following procedure changes the color of the Up skin to change the Lists appearance in its normal inactive state.
1 Create a new Flash file (ActionScript 3.0) document. 2 Drag the List component from the Components panel to the Stage and give it an instance name of aList.
3 Double-click the List to open its palette of skins. 4 Double-click the Cell Renderer skin to open the palette of Cell Renderer skins. 5 Double-click the Up_Skin skin to open it for editing. 6 Click the fill area of the skin to select it. A Fill color picker should appear in the Property inspector with the skins
2 Drag the NumericStepper component from the Components panel to the Stage and give it an instance name of myNs. 3 Add the following code to the Actions panel on Frame 1 of the main Timeline:
var tf:TextFormat = new TextFormat(); myNs.setSize(100, 50); tf.color = 0x0000CC; tf.size = 24; tf.font = "Arial"; tf.align = "center"; myNs.setStyle("textFormat", tf);
NumericStepper skins
1 Create a new FLA file. 2 Drag the NumericStepper component to the Stage. 3 Set the Zoom control to 400% to enlarge the image for editing. 4 Double-click the background of the TextInput skin on the skins panel until you drill down to the Group level and
the background color appears in the Fill color picker in the Property inspector.
5 Using the Fill color picker in the Property inspector, select color #9999FF to apply it to the background of the
TextInput skin.
6 Click the Back button at the left side of the edit bar above the Stage to return to document-editing mode. 7 Double-click the NumericStepper again to reopen the skins panel.
8 Double-click the background of the up arrow button in the Up group until the background is selected and its color
For information on setting skin styles, see About Skins on page 98.
ProgressBar skins
The bar is placed over the track skin, using the barPadding to determine the positioning. The assets are scaled using 9-slice scaling. The indeterminate bar is used when the ProgressBar instances indeterminate property is set to true. The skin is resized vertically and horizontally to fit the size of the ProgressBar. You can edit these skins to change the appearance of the ProgressBar. For example, the following example changes the color of the indeterminate bar.
1 Create a new FLA file. 2 Drag a ProgressBar component to the stage and double-click it to open its panel of skin icons. 3 Double-click the indeterminate bar skin. 4 Set the zoom control to 400% to enlarge the icon for editing. 5 Double-click one of the diagonal bars, then hold down the Shift key and click on each of the others. The current
diagonal bars.
7 Click the Back button at the left side of the edit bar above the Stage to return to document-editing mode. 8 Select Control > Test Movie.
This code sets the textFormat style for the CheckBox, then applies it to the RadioButton by calling the getStyle() method on the CheckBox.
5 Select Control > Test Movie.
RadioButton skins
If a RadioButton is enabled and not selected, it displays its over skin when a user moves the pointer over it. When a user clicks a RadioButton, it receives input focus and displays its selected_down skin. When a user releases the mouse, the RadioButton displays its selected_up skin. If a user moves the pointer out of the RadioButtons hit area while pressing the mouse button, the RadioButton redisplays its up skin. If a RadioButton is disabled, it displays its disabled state, regardless of user interaction.
The following example replaces the selected_up skin that indicates the selected state.
1 Create a new Flash document (ActionScript 3.0). 2 Drag the RadioButton component to the Stage and double-click it to open its palette of skins. 3 Set the zoom control to 800% to enlarge the icon for editing. 4 Double-click the selected_up skin to select it and hit the Delete key to delete it. 5 Select the Rectangle tool on the Tools panel. 6 In the Property inspector, set the line color to red (#FF0000) and the Fill color to black (#000000). 7 Starting at the cross hairs that mark the symbols registration point (also origin point or zero point), click and drag
The RadioButton in the selected state should appear similar to the one in the following illustration.
The registration point (also origin point or zero point) of its content is in the upper-left corner of the pane. When the horizontal scroll bar is turned off, the vertical scroll bar is displayed from top to bottom along the right
side of the scroll pane. When the vertical scroll bar is turned off, the horizontal scroll bar is displayed from left to right along the bottom of the scroll pane. You can also turn off both scroll bars.
If the scroll pane is too small, the content may not display correctly. When the scroll pane is resized, the scroll track and scroll box (thumb) expand or contract, and their hit areas are
resized. The buttons remain the same size.
3 Click the Parameters tab in the Property inspector and enter the following value for the source parameter:
http://www.helpexamples.com/flash/images/image1.jpg.
4 On Frame 1 of the main Timeline, add the following code to the Actions panel.
mySp.setStyle("contentPadding", 5);
Note that the padding is applied between the components border and its content, on the outside of the scroll bars.
5 Select Control > Test Movie.
Slider skins
The following example edits the up track to change its color to blue.
1 Create a new Flash document (ActionScript 3.0). 2 Drag the Slider component from the Components panel to the Stage. 3 Double-click the Slider component to open its skins panel. 4 Double-click the up track on its registration mark to open it in symbol-editing mode. 5 Set the zoom control to 800% to enlarge the icon for editing. Notice that the Sliders track consists of three bars. 6 Click the top bar to select it. When its selected, its color will appear in the Fill color picker in the Property inspector. 7 Using the Fill color picker in the Property inspector, select color #000066 to apply it to the top bar of the Slider track. 8 Click the middle bar of the Slider track to select it. When its selected, its color appears in the Fill color picker in the
Property inspector.
9 Using the Fill color picker in the Property inspector, select color #0066FF to apply it to the middle bar of the Slider
track.
10 Click the bottom bar of the Slider track to select it. When its selected, its color appears in the Fill color picker in
track.
12 Click the Back button at the left side of the edit bar above the Stage to return to document-editing mode. 13 Select Control > Test Movie.
2 Drag a TextArea component to the Stage and give it an instance name of myTa. 3 Add the following code to the Actions panel on Frame 1 of the main Timeline.
var tf:TextFormat = new TextFormat(); tf.color = 0xCC99FF; tf.font = "Arial Narrow"; tf.size = 24; myTa.setStyle("disabledTextFormat", tf); myTa.text = "Hello World"; myTa.setSize(120, 50); myTa.move(200, 50); myTa.enabled = false;
TextArea skins
Note: Changing the ScrollBar skin in one component will change it for all other components that use the ScrollBar. The following procedure changes the border colors of the Focus Rect Skin, which appears when the TextArea has focus, and the Normal skin.
1 Create a new Flash file. 2 Drag a TextArea component to the stage and double-click it to open its panel of skin icons. 3 Double-click the Focus Rect Skin. 4 Click the border of the Focus Rect Skin to select it. When its selected its current color appears in the Fill color picker
10 Click the Back button at the left side of the edit bar above the Stage to return to document-editing mode. 11 Select Control > Test Movie.
When you select the TextArea to begin entering text, its border should appear as shown in the following illustration:
The outer border is the Focus Rect skin and the inner border is the border of the Normal skin. For information about editing the UIScrollBar skin see Customize the UIScrollBar component on page 128.
TextInput caption
The following procedure changes the border and background colors of a TextInput component:
1 Create a new Flash file. 2 Drag a TextInput component to the Stage and double-click it to open its panel of skins. 3 Double-click the Normal skin. 4 Set the zoom control to 800% to enlarge the icon for editing. 5 Select each edge of the Normal skins border, one at a time, and set its color to #993399 to apply it. 6 Double-click the background until its color appears in the Fill color picker in the Property inspector. Select color
2 Drag the TileList component to the Stage and give it an instance name of myTl. 3 Add the following code to the Actions panel on Frame 1 of the Timeline.
myTl.setSize(100, 100); myTl.addItem({label:"#1"}); myTl.addItem({label:"#2"}); myTl.addItem({label:"#3"}); myTl.addItem({label:"#4"}); var tf:TextFormat = new TextFormat(); tf.font = "Arial"; tf.color = 0x00FF00; tf.size = 16; tf.italic = true; tf.bold = true; tf.underline = true; tf.align = "center"; myTl.setRendererStyle("textFormat", tf);
TileList skins
Note: Changing the ScrollBar skin in one component will change it in all other components that use the ScrollBar. The following procedure changes the color of the TileLists CellRenderer Selected_Up skin.
1 Create a Flash document (ActionScript 3.0). 2 Drag the TileList component to the Stage and double-click it to open its panel of skins. 3 Double-click the CellRenderer skin, then double-click the Selected_Up skin, and then click the rectangular
background.
4 Select color #99FFFF using the Fill color picker in the Property inspector to apply it to the Selected_Up skin. 5 Click the Back button at the left side of the edit bar above the Stage until you return to document-editing mode.
6 On the Parameters tab of the Property inspector, double-click the second column of the dataProvider row to open
the Values dialog box. Add items with the following labels: 1st item, 2nd item, 3rd item, 4th item.
7 Select Control > Test Movie. 8 Click one of the cells in the TileList to select it, and then move the mouse away from the selected cell.
UIScrollBar skins
Both horizontal and vertical scroll bars use the same skins; when displaying a horizontal scroll bar the UIScrollBar component rotates the skins as appropriate. Note: Changing the ScrollBar skin in one component will change it in all other components that use the ScrollBar. The following example demonstrates how to change the color of the UIScrollBar's thumb and arrow buttons.
1 Create a new Flash document (ActionScript 3.0). 2 Drag the UIScrollBar component to the Stage and give it an instance name of mySb. In the Parameters tab, set the
direction to horizontal.
3 Double-click the scroll bar to open its panel of skins. 4 Click the Up skin to select it. 5 Set the zoom control to 400% to enlarge the icon for editing. 6 Double-click the background of the right arrow (or up arrow for a vertical scroll bar) until the background is
selected and its color appears in the Fill color picker in the Property inspector.
7 Select color #CC0033 to apply it to the button background. 8 Click the Back button at the left side of the edit bar above the Stage until you return to document-editing mode. 9 Repeat steps 6, 7, and 8 for the thumb and the left-hand arrow (or down arrow for a vertical scroll bar) elements. 10 Add the following code to the Actions panel on Frame 1 of the Timeline to attach the scroll bar to a TextField.
var tf:TextField = new TextField(); addChild(tf); tf.x = 150; tf.y = 100; mySb.width = tf.width = 200; tf.height = 22; tf.text = "All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All . . ."; mySb.y = tf.y + tf.height; mySb.x = tf.x + tf.width;x mySb.scrollTarget = tf;
Horizontal ScrollBar with thumb and left and right arrows in red
131
Can be dragged to the Stage and implemented quickly and successfully Supports full-screen size Provides a collection of predesigned skins that allow you to customize the appearance of its playback controls Allows you to select color and alpha values for predesigned skins Allows advanced users to create their own skins Provides live preview during authoring Provides layout properties to keep the video file centered when resizing Allows start of playback when enough of a progressively downloaded video file has downloaded Provides cue points that allow you to synchronize your video with text, graphics, and animation Maintains a reasonably sized SWF file
The FLVPlayback component includes the FLV Playback Custom UI components. The FLVPlayback component is a combination of the display area, or video player, in which you view the video file and the controls that allow you to operate it. The FLV Playback Custom UI components provide control buttons and mechanisms that you can use to play, stop, pause, and otherwise control the video file. These controls include the BackButton, BufferingBar, CaptionButton (for FLVPlaybackCaptioning), ForwardButton, FullScreenButton, MuteButton, PauseButton, PlayButton, PlayPauseButton, SeekBar, StopButton, and VolumeBar. The FLVPlayback component and the FLV Playback Custom UI controls appear in the Components panel, as shown in the following figure:
The process of adding playback controls to the FLVPlayback component is called skinning. The FLVPlayback component has an initial default skin, SkinOverAll.swf, that provides the play, stop, back, forward, seekbar, mute, volume, full screen, and captioning controls. To change this skin, you have the following choices:
Select from a collection of predesigned skins Create a custom skin and add it to the collection of predesigned skins Select individual controls from the FLV Playback Custom UI components and customize them
When you select a predesigned skin, you can choose the skin color and alpha values separately, either during authoring or at run time. For more information, see Select a predesigned skin on page 149. After you select a different skin, the selected skin becomes the new default skin. For more information about selecting or creating a skin for the FLVPlayback component, see Customize the FLVPlayback component on page 149.
Drag the FLVPlayback component from the Components panel to the Stage, and specify a value for the source
parameter.
Use the Video Import wizard to create the component on the Stage, and customize it by selecting a skin. Use the FLVPlayback() constructor to dynamically create an FLVPlayback instance on the Stage, assuming the
component is in the library.
Note: If you create an FLVPlayback instance with ActionScript, you must also assign a skin to it by setting the skin property with ActionScript. When you apply a skin this way, it is not automatically published with the SWF file. You must copy both the application SWF file and the skin SWF file to your application server or the skin SWF file wont be available when you run the application. Drag the FLVPlayback component from the Components panel 1 In the Components panel, click the Plus (+) button to open the video entry.
2 Drag the FLVPlayback component to the Stage. 3 With the FLVPlayback component selected on the Stage, locate the Value cell for the source parameter on the
Parameters tab of the Component inspector, and enter a string that specifies one of the following:
A local path to a video file A URL to a video file A URL to a synchronized Multimedia Integration Language (SMIL) file that describes how to play a video file
For information on how to create a SMIL file to describe one or more FLV files, see Use a SMIL file on page 159.
4 On the Parameters tab in the Component inspector, with the FLVPlayback component selected on the Stage, click
From the drop-down Skin list, select one of the predesigned skins to attach a set of playback controls to the
component.
If you created a custom skin, select Custom Skin URL from the pop-up menu, and enter, in the URL box, the
URL for the SWF file that contains the skin.
Select None, and drag individual FLV Playback Custom UI components to the Stage to add playback controls.
Note: In the first two cases, a preview of the skin appears in the viewing pane above the pop-up menu. You can use the Color picker to change the color of the skin. To change the color of a custom UI control, you must customize it. For more information on using custom UI controls, see Skin FLV Playback Custom UI components individually on page 150.
7 Click OK to close the Select Skin dialog box. 8 Select Control > Test Movie to execute the SWF file and start the video.
The following procedure uses the Video Import wizard to add an FLVPlayback component: Use the Video Import wizard: 1 Select File > Import > Import Video.
2 Indicate the location of the video file by selecting one of the following options:
On my local computer Already deployed to a web server, Flash Video Streaming Service, or Flash Media Server
3 Depending on your choice, enter either the path or the URL that specifies the location of the video file, then click Next. 4 If you selected a file path, youll see a Deployment dialog box next in which you can select one of the options listed
Stream from Flash Video Streaming Service Stream from Flash Media Server Embed video in a SWF file and play in the Timeline
Important: Do not select the Embed Video option. The FLVPlayback component plays only external streaming video. This option will not place an FLVPlayback component on the Stage.
5 Click Next. 6 Select one of the following options:
From the drop-down Skin list, select one of the predesigned skins to attach a set of playback controls to the
component.
If you created a custom skin for the component, select Custom Skin URL from the pop-up menu, and enter the
URL for the SWF file that contains the skin in the URL box.
Select None, and drag individual FLV Playback Custom UI components to the Stage to add playback controls.
Note: In the first two cases, a preview of the skin appears in the viewing pane above the pop-up menu.
7 Click OK to close the Select Skin dialog box. 8 Read the Finish Video Import dialog box to note what happens next, and then click Finish. 9 If you have not saved your FLA file, a Save As dialog box appears. 10 Select Control > Test Movie to execute the SWF, and start the video.
The following procedure adds the FLVPlayback component using ActionScript. Create an instance dynamically using ActionScript: 1 Drag the FLVPlayback component from the Components panel to the Library panel (Window > Library).
2 Add the following code to the Actions panel on Frame 1 of the Timeline. Change install_drive to the drive on which
you installed Flash and modify the path to reflect the location of the Skins folder for your installation: On a Windows computer:
import fl.video.*; var my_FLVPlybk = new FLVPlayback(); my_FLVPlybk.x = 100; my_FLVPlybk.y = 100; addChild(my_FLVPlybk); my_FLVPlybk.skin = "file:///install_drive|/Program Files/Adobe/Adobe Flash CS5/en/Configuration/FLVPlayback Skins/ActionScript 3.0/SkinOverPlaySeekMute.swf" my_FLVPlybk.source = "http://www.helpexamples.com/flash/video/water.flv";
On a Macintosh computer:
import fl.video.*; var my_FLVPlybk = new FLVPlayback(); my_FLVPlybk.x = 100; my_FLVPlybk.y = 100; addChild(my_FLVPlybk); my_FLVPlybk.skin = "file:///Macintosh HD:Applications:Adobe Flash CS5:Configuration:FLVPlayback Skins:ActionScript 3.0SkinOverPlaySeekMute.swf" my_FLVPlybk.source = "http://www.helpexamples.com/flash/video/water.flv";
Note: If you do not set the source and skin properties, the generated movie clip appears to be empty.
3 Select Control > Test Movie to execute the SWF file and start the video file.
The Content Path dialog box provides a check box, Match Source FLV Dimensions, that specifies whether the FLVPlayback instance on the Stage should match the dimensions of the source video file. The source video file contains preferred height and width dimensions for playing. If you select this option, the dimensions of the FLVPlayback instance are resized to match these preferred dimensions. The source Enter the URL or local path for either the video file or an XML file that describes how to play the video file. If you do not know the exact location of a video file, click the folder icon to open a Browser dialog box to help you find the correct location. When browsing for a video file, if it is at or below the location of the target SWF file, Flash automatically makes the path relative to that location so you can serve it from a web server. Otherwise, the path is an absolute Windows or Macintosh path. To enter the name of a local XML file, type the path and name. If you specify an HTTP URL, the video file plays as a progressive download. If you specify a URL that is an RTMP URL, the video file streams from Flash Media Server or FVSS. A URL to an XML file could also be a streaming video file from Flash Media Server or FVSS. Important: You can also specify the location of a SMIL file that describes how to play multiple video file streams for multiple bandwidths. The file uses the Synchronized Multimedia Integration Language (SMIL) to describe the FLV files. For a description of the SMIL file, see Use a SMIL file on page 159. You can also specify the name and location of the video file using the ActionScript FLVPlayback.source property and the FLVPlayback.play() and FLVPlayback.load() methods. These three alternatives take precedence over the source parameter in the Component inspector. For more information, see the FLVPlayback.source, FLVPlayback.play(), and FLVPlayback.load() entries for the FLVPlayback class in the ActionScript 3.0 Reference for Flash Professional.
Full-screen support
The ActionScript 3.0 version of the FLVPlayback component supports full-screen mode, which requires Flash Player 9.0.28.0, or later, and also that the HTML is set up correctly for full-screen viewing. Some predesigned skins include a toggle button to switch full-screen mode on and off. The FullScreenButton icon appears on the right side of the control bar in the following illustration.
Full-screen support occurs only if the fullScreenTakeOver property is set to true, which it is by default. Full-screen support can occur with or without hardware-acceleration support. For information about hardwareacceleration support, see Hardware acceleration on page 139. To implement full-screen support for FLVPlayback: 1 Add the FLVPlayback component to your application and assign a video file to it.
2 Select a skin for the FLVPlayback component that has the full-screen button (e.g.,
SkinUnderPlaySeekFullscreen.swf) or add the FullScreenButton user-interface component to the FLVPlayback component from the Video section in the Components panel.
3 Select File > Publish Settings. 4 In the Publish Settings dialog, click the HTML tab. 5 On the HTML tab, select Flash With Full Screen Support from the Template pop-up menu. 6 Also on the HTML tab, select the Detect Flash Version check box and specify a version of 9.0.28 or later, depending
As an alternative to step 7, you can click OK and then select File > Publish Preview > Default - (HTML) to automatically open the exported HTML file in your default browser. Otherwise, open the exported HTML file with your browser to test the full-screen option. To add the FLVPlayback component with full-screen support to your web page, open the exported HTML file and copy the code that embeds the SWF file into the HTML file for your web page. This code should look similar to the following example:
//from the <head> section <script language="javascript"> AC_FL_RunContent = 0; </script> <script language="javascript"> DetectFlashVer = 0; </script> <script src="AC_RunActiveContent.js" language="javascript"></script> <script language="JavaScript" type="text/javascript"> <!-// ----------------------------------------------------------------------------// Globals // Major version of Flash required var requiredMajorVersion = 9; // Minor version of Flash required var requiredMinorVersion = 0; // Revision of Flash required var requiredRevision = 28; // ----------------------------------------------------------------------------// --> </script> //and from the <body> section <script language="JavaScript" type="text/javascript"> <!-if (AC_FL_RunContent == 0 || DetectFlashVer == 0) { alert("This page requires AC_RunActiveContent.js."); } else { var hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision); if(hasRightVersion) { // if we've detected an acceptable version // embed the Flash movie AC_FL_RunContent( 'codebase', 'http://download.macromedia.com/pub/ shockwave/cabs/flash/swflash.cab#version=9,0,28,0', 'width', '550', 'height', '400', 'src', 'fullscreen', 'quality', 'high', 'pluginspage', 'http://www.macromedia.com/go/ getflashplayer', 'align', 'middle', 'play', 'true', 'loop', 'true', 'scale', 'showall', 'wmode', 'window', 'devicefont', 'false', 'id', 'fullscreen', 'bgcolor', '#ffffff', 'name', 'fullscreen', 'menu', 'true', 'allowScriptAccess','sameDomain',
'allowFullScreen','true', 'movie', 'fullscreen', 'salign', '' ); //end AC code } else { // Flash is too old or we can't detect the plug-in. var alternateContent = 'Alternative HTML content should be placed here.' + 'This content requires Adobe Flash Player.' + '<a href=http://www.macromedia.com/go/getflash/>Get Flash</a> '; document.write(alternateContent); // Insert non-Flash content. } } // --> </script> <noscript> // Provide alternative content for browsers that do not support scripting // or for those that have scripting disabled. Alternative HTML content should be placed here. This content requires Adobe Flash Player. <a href="http://www.macromedia.com/go/getflash/">Get Flash</a> </noscript>
As an alternative, you can use the exported HTML file as the template for your web page and add your other content to it. If you do this, however, change the name of the HTML file so that you don't accidentally overwrite it in the event that you later export the FLVPlayback HTML file from Flash again. In any case, you must also upload to your web server the AC_RunActiveContent.js file that is exported to the same folder as the HTML file. ActionScript support for full-screen mode includes the fullScreenBackgroundColor, fullScreenSkinDelay, and fullScreenTakeOver properties and the enterFullScreenDisplayState() method. For information on these ActionScript elements, see the ActionScript 3.0 Reference for Flash Professional.
Use enterFullScreenDisplayState()
You can also invoke full-screen mode by calling the enterFullScreenDisplayState() ActionScript method, as shown in the following example.
function handleClick(e:MouseEvent):void { myFLVPlybk.enterFullScreenDisplayState(); } myButton.addEventListener(MouseEvent.CLICK, handleClick);
In this example, full-screen mode is not invoked by clicking the full-screen toggle button on an FLVPlayback skin, but rather, by clicking a button (MyButton) that the creator of the web page included to invoke full-screen mode. Clicking the button triggers the handleClick event handler, which calls the enterFullScreen DisplayState() method. The enterFullScreenDisplayState() method sets the Stage.displayState property to StageDisplayState.FULL_SCREEN, and therefore carries the same restrictions as the displayState property. For more information on the enterFullScreenDisplayState() method and the Stage.displayState property, see the ActionScript 3.0 Reference for Flash Professional.
Hardware acceleration
Flash Player 9.0.115.0 and later versions include code that takes advantage of available video hardware to improve the performance and fidelity of FLV files that FLVPlayback plays in full-screen mode. If the prerequisites are met and the fullScreenTakeOver property is set to true, Flash Player uses hardware acceleration to scale the video file, rather than scaling it through software. If the FLVPlayback component runs in an earlier version of Flash Player, or if the prerequisites for hardware acceleration do not exist, Flash Player scales up the video file itself, as it did previously. To take advantage of hardware acceleration for full-screen support, your computer must have a DirectX 7-compatible video card with 4 MB or more of VRAM (video RAM). This hardware support is available in Windows 2000 or Mac OS X 10.2, and later versions of those operating systems. Direct X provides APIs that comprise an interface between software and the video hardware to accelerate three-dimensional and two-dimensional graphics, among other things. To take advantage of hardware-acceleration mode, you must also invoke full-screen mode in one of the following ways:
Using the full-screen toggle button on an FLVPlayback skin Using the FullScreenButton video control Using the ActionScript enterFullScreenDisplayState() method. For more information, see Use
enterFullScreenDisplayState() on page 138. If you invoke full-screen mode by setting the Stage.displayState property to StageDisplayState.FULLSCREEN, FLVPlayback does not use hardware acceleration, even if the video hardware and memory are available. One consequence of using hardware acceleration for full-screen support is that the FLVPlayback skins are scaled along with the video player and the video file. The following image shows the effect of full-screen mode with hardware acceleration on the FLVPlayback skin, a detail of which is shown here at full resolution.
This image shows the result of using full-screen mode on a 1600 x 1200 monitor with a video file that has a width of 320 and a height of 240, which are the default FLVPlayback dimensions. The distortion effect on the skin is more pronounced on FLV files with smaller dimensions or on a larger monitor. Conversely, the distortion effect is less pronounced on larger FLV files or on smaller monitors. For example, changing from 640 x 480 to 1600 x 1200 still increases the size of the skin, but it looks less distorted.
You can set the skinScaleMaximum property to limit the scaling of the FLVPlayback skin. The default value is 4.0, or 400%. Limiting the scaling of the skin, however, requires a combination of hardware and software to scale the FLV and this can adversely affect performance on FLVs with large dimensions that are encoded at a high bit rate. If the video is large (640 pixels wide or more, 480 pixels tall or more, for example), you should not set skinScaleMaximum to a small value because it could cause large performance problems on large display monitors. The skinScaleMaximum property allows you to manage the trade offs between performance and quality and the appearance of a large skin.
A navigation cue point allows you to seek a particular frame in the FLV file because it creates a keyframe within the FLV file as near as possible to the time that you specify. A keyframe is a data segment that occurs between image frames in the FLV file stream. When you seek a navigation cue point, the component seeks to the keyframe and starts the cuePoint event. An event cue point enables you to synchronize a point in time within the FLV file with an external event on the web page. The cuePoint event occurs precisely at the specified time. You can embed navigation and event cue points in an FLV file using either the Video Import wizard or the Flash Video Encoder. For more information on the Video Import wizard and the Flash Video encoder, see Chapter 16, Working with Video, in Using Flash. An ActionScript cue point is an external cue point that you can add either through the components Flash Video Cue Points dialog box or through the FLVPlayback.addASCuePoint() method. The component stores and tracks ActionScript cue points apart from the FLV file, and consequently, they are less accurate than embedded cue points. ActionScript cue points are accurate to a tenth of a second. You can increase the accuracy of ActionScript cue points by lowering the value of the playheadUpdateInterval property because the component generates the cuePoint event for ActionScript cue points when the playhead updates. For more information, see the FLVPlayback.playheadUpdateInterval property in the ActionScript 3.0 Reference for Flash Professional. In ActionScript and within the FLV files metadata, a cue point is represented as an object with the following properties: name, time, type, and parameters. The name property is a string that contains the assigned name of the cue point. The time property is a number representing the time in hours, minutes, seconds, and milliseconds (HH:MM:SS.mmm) when the cue point occurs. The type property is a string whose value is "navigation", "event", or "actionscript", depending on the type of cue point that you created. The parameters property is an array of specified name and value pairs. When a cuePoint event occurs, the cue point object is available in the event object through the info property.
The dialog box displays embedded and ActionScript cue points. You can use this dialog box to add and delete ActionScript cue points as well as cue point parameters. You can also enable or disable embedded cue points. However, you cannot add, change, or delete embedded cue points. Add an ActionScript cue point: 1 Click the Value cell of the cuePoints parameter in the Component parameters to open the Cue Points dialog at the bottom of the Property inspector. (In Flash Professional CS4, double-click the value cell of the cuePoints parameter in the Component inspector to open the Flash Cue Points dialog box.)
2 Click the plus (+) sign in the upper-left corner, above the list of cue points, to add a default ActionScript cue point
entry.
3 Click the New Cue Point text in the Name column, and edit the text to name the cue point. 4 Click the Time value of 00:00:00:000 to edit it, and assign a time for the cue point to occur. You can specify the time
in hours, minutes, seconds, and milliseconds (HH:MM:SS.mmm). If multiple cue points exist, the dialog box moves the new cue point to its chronological position in the list.
5 To add a parameter for the selected cue point, click the plus (+) sign above the Parameters section, and enter values
in the Name and Value columns. Repeat this step for each parameter.
6 To add more ActionScript cue points, repeat steps 2 through 5 for each one. 7 Press Enter to save your changes. (In Flash Professional CS4, Click OK to save your changes.)
Delete an ActionScript cue point: 1 Click the value cell of the cuePoints parameter. (In Flash Professional CS4, double-click the Value cell of the cuePoints parameter in the Component inspector to open the Flash Cue Points dialog box.)
2 Select the cue point that you want to delete. 3 Click the minus (-) sign in the upper-left corner, above the list of cue points, to delete it. 4 Repeat steps 2 and 3 for each cue point that you want to delete. 5 Press Enter to save your changes. (In Flash Professional CS4, Click OK to save your changes.)
To enable or disable an embedded FLV file cue point: 1 Click the value cell of the cuePoints parameter. (In Flash Professional CS4, double-click the value cell of the cuePoints parameter in the Component inspector to open the Flash Cue Points dialog box.)
2 Select the cue point you want to enable or disable. 3 Click the value in the Type column to trigger the pop-up menu, or click the down arrow. 4 Click the name of the type of cue point (for example, Event or Navigation) to enable it. Click Disabled to disable it. 5 Press Enter to save your changes. (In Flash Professional CS4, Click OK to save your changes.)
Add ActionScript cue points You can add ActionScript cue points to an FLV file using the addASCuePoint() method. The following example adds two ActionScript cue points to the FLV file when it is ready to play. It adds the first cue point using a cue point object, which specifies the time, name, and type of the cue point in its properties. The second call specifies the time and name using the methods time and name parameters.
// Requires an FLVPlayback instance called my_FLVPlybk on Stage import fl.video.*; import fl.video.MetadataEvent; my_FLVPlybk.source = "http://www.helpexamples.com/flash/video/cuepoints.flv" var cuePt:Object = new Object(); //create cue point object cuePt.time = 2.02; cuePt.name = "ASpt1"; cuePt.type = "actionscript"; my_FLVPlybk.addASCuePoint(cuePt);//add AS cue point // add 2nd AS cue point using time and name parameters my_FLVPlybk.addASCuePoint(5, "ASpt2");
For more information, see the FLVPlayback.addASCuePoint() method in the ActionScript 3.0 Reference for Flash Professional. Listen for cuePoint events The cuePoint event allows you to receive control in your ActionScript code when a cuePoint event occurs. When cue points occur in the following example, the cuePoint listener calls an event handler function that displays the value of the playheadTime property and the name and type of the cue point. Use this example in combination with the example in the preceding section, Add ActionScript cue points, to see the results.
my_FLVPlybk.addEventListener(MetadataEvent.CUE_POINT, cp_listener); function cp_listener(eventObject:MetadataEvent):void { trace("Elapsed time in seconds: " + my_FLVPlybk.playheadTime); trace("Cue point name is: " + eventObject.info.name); trace("Cue point type is: " + eventObject.info.type); }
For more information on the cuePoint event, see the FLVPlayback.cuePoint event in the ActionScript 3.0 Reference for Flash Professional. Find cue points Using ActionScript, you can find a cue point of any type, find the nearest cue point to a time, or find the next cue point with a specific name. The ready_listener() event handler in the following example calls the findCuePoint() method to find the cue point ASpt1 and then calls the findNearestCuePoint() method to find the navigation cue point that is nearest to the time of cue point ASpt1:
import fl.video.FLVPlayback; import fl.video.CuePointType; import fl.video.VideoEvent; my_FLVPlybk.source = "http://www.helpexamples.com/flash/video/cuepoints.flv" var rtn_obj:Object; //create cue point object my_FLVPlybk.addASCuePoint(2.02, "ASpt1");//add AS cue point function ready_listener(eventObject:VideoEvent):void { rtn_obj = my_FLVPlybk.findCuePoint("ASpt1", CuePointType.ACTIONSCRIPT); traceit(rtn_obj); rtn_obj = my_FLVPlybk.findNearestCuePoint(rtn_obj.time, CuePointType.NAVIGATION); traceit(rtn_obj); } my_FLVPlybk.addEventListener(VideoEvent.READY, ready_listener); function traceit(cuePoint:Object):void { trace("Cue point name is: " + cuePoint.name); trace("Cue point time is: " + cuePoint.time); trace("Cue point type is: " + cuePoint.type); }
In the following example, the ready_listener() event handler finds cue point ASpt and calls the findNextCuePointWithName() method to find the next cue point with the same name:
import fl.video.*; my_FLVPlybk.source = "http://www.helpexamples.com/flash/video/cuepoints.flv" var rtn_obj:Object; //create cue point object my_FLVPlybk.addASCuePoint(2.02, "ASpt");//add AS cue point my_FLVPlybk.addASCuePoint(3.4, "ASpt");//add 2nd Aspt my_FLVPlybk.addEventListener(VideoEvent.READY, ready_listener); function ready_listener(eventObject:VideoEvent):void { rtn_obj = my_FLVPlybk.findCuePoint("ASpt", CuePointType.ACTIONSCRIPT); traceit(rtn_obj); rtn_obj = my_FLVPlybk.findNextCuePointWithName(rtn_obj); traceit(rtn_obj); } function traceit(cuePoint:Object):void { trace("Cue point name is: " + cuePoint.name); trace("Cue point time is: " + cuePoint.time); trace("Cue point type is: " + cuePoint.type); }
For more information about finding cue points, see the FLVPlayback.findCuePoint(), FLVPlayback.findNearestCuePoint(), and FLVPlayback.findNextCuePointWithName() methods in the ActionScript 3.0 Reference for Flash Professional. Seek navigation cue points You can seek a navigation cue point, seek the next navigation cue point from a specified time, and seek the previous navigation cue point from a specified time. The following example plays the FLV file cuepoints.flv and seeks the cue point at 7.748 when the ready event occurs. When the cuePoint event occurs, the example calls the seekToPrevNavCuePoint() method to seek the first cue point. When that cuePoint event occurs, the example calls the seekToNextNavCuePoint() method to seek the last cue point by adding 10 seconds to eventObject.info.time, which is the time of the current cue point.
import fl.video.*; my_FLVPlybk.addEventListener(VideoEvent.READY, ready_listener); function ready_listener(eventObject:Object):void { my_FLVPlybk.seekToNavCuePoint("point2"); } my_FLVPlybk.addEventListener(MetadataEvent.CUE_POINT, cp_listener); function cp_listener(eventObject:MetadataEvent):void { trace(eventObject.info.time); if(eventObject.info.time == 7.748) my_FLVPlybk.seekToPrevNavCuePoint(eventObject.info.time - .005); else my_FLVPlybk.seekToNextNavCuePoint(eventObject.info.time + 10); } my_FLVPlybk.source = "http://helpexamples.com/flash/video/cuepoints.flv";
For more information, see the FLVPlayback.seekToNavCuePoint(), FLVPlayback.seekToNextNavCuePoint(), and FLVPlayback.seekToPrevNavCuePoint() methods in the ActionScript 3.0 Reference for Flash Professional. Enable and disable embedded FLV file cue points You can enable and disable embedded FLV file cue points using the setFLVCuePointEnabled() method. Disabled cue points do not trigger cuePoint events and do not work with the seekToCuePoint(), seekToNextNavCuePoint(), or seekToPrevNavCuePoint() methods. You can find disabled cue points, however, with the findCuePoint(), findNearestCuePoint(), and findNextCuePointWithName() methods. You can test whether an embedded FLV file cue point is enabled using the isFLVCuePointEnabled() method. The following example disables the embedded cue points point2 and point3 when the video is ready to play. When the first cuePoint event occurs, however, the event handler tests to see whether cue point point3 is disabled and, if so, enables it.
import fl.video.*; my_FLVPlybk.source = "http://www.helpexamples.com/flash/video/cuepoints.flv"; my_FLVPlybk.addEventListener(VideoEvent.READY, ready_listener); function ready_listener(eventObject:VideoEvent):void { my_FLVPlybk.setFLVCuePointEnabled(false, "point2"); my_FLVPlybk.setFLVCuePointEnabled(false, "point3"); } my_FLVPlybk.addEventListener(MetadataEvent.CUE_POINT, cp_listener); function cp_listener(eventObject:MetadataEvent):void { trace("Cue point time is: " + eventObject.info.time); trace("Cue point name is: " + eventObject.info.name); trace("Cue point type is: " + eventObject.info.type); if (my_FLVPlybk.isFLVCuePointEnabled("point2") == false) { my_FLVPlybk.setFLVCuePointEnabled(true, "point2"); } }
For more information, see the FLVPlayback.isFLVCuePointEnabled() and FLVPlayback.setFLVCuePointEnabled() methods in the ActionScript 3.0 Reference for Flash Professional. Remove an ActionScript cue point You can remove an ActionScript cue point using the removeASCuePoint() method. The following example removes the cue point ASpt2 when cue point ASpt1 occurs:
import fl.video.*; my_FLVPlybk.source = "http://www.helpexamples.com/flash/video/cuepoints.flv" my_FLVPlybk.addASCuePoint(2.02, "ASpt1");//add AS cue point my_FLVPlybk.addASCuePoint(3.4, "ASpt2");//add 2nd Aspt my_FLVPlybk.addEventListener(MetadataEvent.CUE_POINT, cp_listener); function cp_listener(eventObject:MetadataEvent):void { trace("Cue point name is: " + eventObject.info.name); if (eventObject.info.name == "ASpt1") { my_FLVPlybk.removeASCuePoint("ASpt2"); trace("Removed cue point ASpt2"); } }
For more information, see FLVPlayback.removeASCuePoint() in the ActionScript 3.0 Reference for Flash Professional.
/** Requires: - FLVPlayback component on the Stage with an instance name of my_FLVPlybk */ // add a cue point to the default player import fl.video.*; my_FLVPlybk.source = "http://www.helpexamples.com/flash/video/clouds.flv"; my_FLVPlybk.addASCuePoint(3, "1st_switch"); my_FLVPlybk.addEventListener(VideoEvent.READY, ready_listener); function ready_listener(eventObject:VideoEvent):void { // add a second video player and create a cue point for it my_FLVPlybk.activeVideoPlayerIndex = 1; my_FLVPlybk.source = "http://www.helpexamples.com/flash/video/water.flv"; my_FLVPlybk.addASCuePoint(3, "2nd_switch"); my_FLVPlybk.activeVideoPlayerIndex = 0; };
To switch to another FLV file while one is playing, you must make the switch in your ActionScript code. Cue points allow you to intervene at specific points in the FLV file using a cuePoint event. The following code creates a listener for the cuePoint event and calls a handler function that pauses the active video player (0), switches to the second player (1), and plays its FLV file:
import fl.video.*; // add listener for a cuePoint event my_FLVPlybk.addEventListener(MetadataEvent.CUE_POINT, cp_listener); // add the handler function for the cuePoint event function cp_listener(eventObject:MetadataEvent):void { // display the no. of the video player causing the event trace("Hit cuePoint event for player: " + eventObject.vp); // test for the video player and switch FLV files accordingly if (eventObject.vp == 0) { my_FLVPlybk.pause(); //pause the first FLV file my_FLVPlybk.activeVideoPlayerIndex = 1; // make the 2nd player active my_FLVPlybk.visibleVideoPlayerIndex = 1; // make the 2nd player visible my_FLVPlybk.play(); // begin playing the new player/FLV } else if (eventObject.vp == 1) { my_FLVPlybk.pause(); // pause the 2nd FLV my_FLVPlybk.activeVideoPlayerIndex = 0; // make the 1st player active my_FLVPlybk.visibleVideoPlayerIndex = 0; // make the 1st player visible my_FLVPlybk.play(); // begin playing the 1st player } } my_FLVPlybk.addEventListener(VideoEvent.COMPLETE, complete_listener); function complete_listener(eventObject:VideoEvent):void { trace("Hit complete event for player: " + eventObject.vp); if (eventObject.vp == 0) { my_FLVPlybk.activeVideoPlayerIndex = 1; my_FLVPlybk.visibleVideoPlayerIndex = 1; my_FLVPlybk.play(); } else { my_FLVPlybk.closeVideoPlayer(1); } };
When you create a new video player, the FLVPlayback instance sets its properties to the value of the default video player, except for the source, totalTime, and isLive properties, which the FLVPlayback instance always sets to the default values: empty string, 0, and false, respectively. It sets the autoPlay property, which defaults to true for the default video player, to false. The cuePoints property has no effect, and it has no effect on a subsequent load into the default video player. The methods and properties that control volume, positioning, dimensions, visibility, and the user interface controls are always global and their behavior is not affected by setting the activeVideoPlayerIndex property. For more information on these methods and properties and the effect of setting the activeVideoPlayerIndex property, see the FLVPlayback.activeVideoPlayerIndex property in the ActionScript 3.0 Reference for Flash Professional. The remaining properties and methods target the video player identified by the value of the activeVideoPlayerIndex property. Properties and methods that control dimensions dointeract with the visibleVideoPlayerIndex property, however. For more information, see the FLVPlayback.visibleVideoPlayerIndex property in the ActionScript 3.0 Reference for Flash Professional.
2 Copy the main.asc file into the my_application folder. 3 Create a folder named streams in the my_application folder. 4 Create a folder named _definst_ inside the streams folder. 5 Place your FLV files in the _definst_ folder.
Skins that are listed in the Skin pop-up menu are located in the Flash application folder /Flash Configuration/FLVPlayback Skins/ActionScript 3.0. You can make new skins available to this dialog box by creating them and placing the SWF file in the folder. The name appears in the pop-up menu with a .swf extension. For more information about creating a skin set, see Create a new skin on page 155.
For skins that you assign by setting the skin property, either by setting the skin parameter during authoring or with ActionScript at run time, you can assign color and alpha (transparency) values independent of choosing the skin. To assign color and alpha values during authoring, open the Color picker in the Skin Select dialog box, as shown here.
To choose the color, click a swatch in the panel or enter its numeric value in the text box. To choose the alpha value, use the slider or type a percentage in the Alpha text box. To assign color and alpha values during run time, set the skinBackgroundColor and skinBackgroundAlpha properties. Set the skinBackgroundColor property to a 0xRRGGBB (red, green, blue) value. Set the skinBackgroundAlpha property to a number between 0.0 and 1.0. The following example sets skinBackgroundColor to 0xFF0000 (red) and skinBackgroundAlpha to .5.
my_FLVPlybk.skinBackgroundColor = 0xFF0000; my_FLVPlybk.skinBackgroundAlpha = .5;
The default values are the last values chosen by the user. If you want to skin the FLVPlayback component using the FLV Playback Custom UI components, select None from the pop-up menu.
Button components
The button components have a similar structure. The buttons include the BackButton, ForwardButton, MuteButton, PauseButton, PlayButton, PlayPauseButton, and StopButton. Most have a single movie clip on Frame 1 with the instance name placeholder_mc. This is usually an instance of the normal state for the button, but not necessarily so. On Frame 2, there are four movie clips on the Stage for each display state: normal, over, down, and disabled. (At run time, the component never actually goes to Frame 2; these movie clips are placed here to make editing more convenient and to force them to load into the SWF file without selecting the Export in First Frame check box in the Symbol Properties dialog box. You must still select the Export for ActionScript option, however.) To skin the button, you simply edit each of these movie clips. You can change their size as well as their appearance. Some ActionScript usually appears on Frame 1. You should not need to change this script. It simply stops the playhead on Frame 1 and specifies which movie clips to use for which states. PlayPauseButton, MuteButton, FullScreenButton, and CaptionButton buttons The PlayPauseButton, MuteButton, FullScreenButton, and CaptionButton buttons are set up differently than the other buttons; they have only one frame with two layers and no script. On that frame, there are two buttons, one on top of the otherin the case of PlayPauseButton, a Play and a Pause button; in the case of MuteButton, a Mute-on and a Mute-off button; in the case of FullScreenButton, a full-screen-on and a full-screen-off button; in the case of CaptionButton, a caption-on and a caption-off button. To skin these buttons, skin each of these two internal buttons as described in Skin FLV Playback Custom UI components individually on page 150; no additional action is required. The CaptionButton is for the FLVPlaybackCaptioning component and must be attached to that component and not the FLVPlayback component. BackButton and ForwardButton buttons The BackButton and ForwardButton buttons are also set up differently than the other buttons. On Frame 2, they have extra movie clips that you can use as a frame around one or both of the buttons. These movie clips are not required and have no special capability; they are provided only as a convenience. To use them, simply drag them on the Stage from your Library panel and place them where you want them. If you dont want them, either dont use them or delete them from your Library panel. Most of the buttons, as supplied, are based on a common set of movie clips so that you can change the appearance of all the buttons at once. You can use this capability, or you can replace those common clips and make every button look different.
BufferingBar component
The buffering bar component is simple: It consists of an animation that is made visible when the component enters the buffering state, and it does not require any special ActionScript to configure it. By default, it is a striped bar moved from left to right with a rectangular mask on it to give it a barber pole effect, but there is nothing special about this configuration. Although the buffering bars in the skin SWF files use 9-slice scaling because they need to be scaled at run time, the BufferingBar FLV Custom UI Component does not and cannot use 9-slice scaling because it has nested movie clips. If you want to make the BufferingBar wider or taller, you might want to change its contents rather than scale it.
There are many places where the ActionScript code in the FLVPlayback component assumes that the registration point (also origin point or zero point) of your SeekBar or VolumeBar component is at the upper-left corner of the content, so it is important to maintain this convention. Otherwise, you might have problems with handles and with progress and fullness movie clips. Although the seek bars in the skin SWF files use 9-slice scaling because they need to be scaled at run time, the SeekBar FLV Custom UI component does not and cannot use 9-slice scaling because it has nested movie clips. If you want to make the SeekBar wider or taller, you might want to change its contents rather than scale it. Handle An instance of the handle movie clip is on Frame 2. As with the BackButton and ForwardButton components, the component never actually goes to Frame 2; these movie clips are placed here to make editing more convenient and as a way to force them to be loaded into the SWF file without selecting the Export in First Frame check box in the Symbol Properties dialog box. You still must select the Export for ActionScript option, however. You might notice that the handle movie clip has a rectangle in the background with alpha set to 0. This rectangle increases the size of the handles hit area, making it easier to grab without changing its appearance, similar to the hit state of a button. Because the handle is created dynamically at run time, it must be a movie clip and not a button. This rectangle with alpha set to 0 is not necessary for any other reason and, generally, you can replace the inside of the handle with any image you want. It works best, however, to keep the registration point centered horizontally in the middle of the handle movie clip. The following ActionScript code is on Frame 1 of the SeekBar component to manage the handle:
stop(); handleLinkageID = "SeekBarHandle"; handleLeftMargin = 2; handleRightMargin = 2; handleY = 11;
The call to the stop() function is necessary due to the content of Frame 2. The second line specifies which symbol to use as the handle, and you should not need to change this if you simply edit the handle movie clip instance on Frame 2. At run time, the FLVPlayback component creates an instance of the specified movie clip on the Stage as a sibling of the Bar component instance, which means that they have the same parent movie clip. So, if your bar is at the root level, your handle must also be at the root level. The variable handleLeftMargin determines the handles original location (0%), and the variable handleRightMargin determines where it is at the end (100%). The numbers give the offsets from the left and right ends of the bar control, with positive numbers marking the limits within the bar and negative numbers marking the limits outside the bar. These offsets specify where the handle can go, based on its registration point. If you put your registration point in the middle of the handle, the handles far left and right sides will go past the margins. A seek bar movie clip must have its registration point as the upper-left corner of its content to work properly. The variable handleY determines the y position of the handle, relative to the bar instance. This is based on the registration points of each movie clip. The registration point in the sample handle is at the tip of the triangle to place it relative to the visible part, disregarding the invisible hit state rectangle. Also, the bar movie clip must keep its registration point as the upper-left corner of its content to work properly. So, for example, with these limits, if a bar control is set at (100, 100) and it is 100 pixels wide, the handle can range from 102 to 198 horizontally and stay at 111 vertically. If you change the handleLeftMargin and handleRightMargin to -2 and handleY to -11, the handle can range from 98 to 202 horizontally and stay at 89 vertically.
Progress and fullness movie clips The SeekBar component has a progress movie clip and the VolumeBar has a fullness movie clip, but in practice, any SeekBar or VolumeBar can have either, neither, or both of these movie clips. They are structurally the same and behave similarly but track different values. A progress movie clip fills up as the FLV file downloads (which is useful for an HTTP download only, because it is always full if streaming from FMS) and a fullness movie clip fills up as the handle moves from left to right. The FLVPlayback component finds these movie clip instances by looking for a specific instance name, so your progress movie clip instance must have your bar movie clip as its parent and have the instance name progress_mc. The fullness movie clip instance must have the instance name fullness_mc. You can set the progress and fullness movie clips with or without the fill_mc movie clip instance nested inside. The VolumeBar fullness_mc movie clip shows the method with the fill_mc movie clip, and the SeekBar progress_mc movie clip shows the method without the fill_mc movie clip. The method with the fill_mc movie clip nested inside is useful when you want a fill that cannot be scaled without distorting the appearance. In the VolumeBar fullness_mc movie clip, the nested fill_mc movie clip instance is masked. You can either mask it when you create the movie clip, or a mask will be created dynamically at run time. If you mask it with a movie clip, name the instance mask_mc and set it up so that fill_mc appears as it would when percentage is 100%. If you do not mask fill_mc, the dynamically created mask will be rectangular and the same size as fill_mc at 100%. The fill_mc movie clip is revealed with the mask in one of two ways, depending on whether fill_mc.slideReveal is true or false. If fill_mc.slideReveal is true, then fill_mc is moved from left to right to expose it through the mask. At 0%, it is all the way to the left, so none of it shows through the mask. As the percentage increases, it moves to the right, until at 100%, it is back where it was created on the Stage. If fill_mc.slideReveal is false or undefined (the default behavior), the mask will be resized from left to right to reveal more of fill_mc. When it is at 0%, the mask will be scaled to 05 horizontally, and as the percentage increases, the scaleX increases until, at 100%, it reveals all of fill_mc. This is not necessarily scaleX = 100 because mask_mc might have been scaled when it was created. The method without fill_mc is simpler than the method with fill_mc, but it distorts the fill horizontally. If you do not want that distortion, you must use fill_mc. The SeekBar progress_mc illustrates this method. The progress or fullness movie clip is scaled horizontally based on the percentage. At 0%, the instances scaleX is set to 0, making it invisible. As the percentage grows, the scaleX is adjusted until, at 100%, the clip is the same size it was on the Stage when it was created. Again, this is not necessarily scaleX = 100 because the clip instance might have been scaled when it was created.
//FLVPlayback instance = my_FLVPlybk my_FLVPlybk.playButton = playbtn; // set playButton prop. to playbtn, etc. my_FLVPlybk.pauseButton = pausebtn; my_FLVPlybk.playPauseButton = playpausebtn; my_FLVPlybk.stopButton = stopbtn; my_FLVPlybk.muteButton = mutebtn; my_FLVPlybk.backButton = backbtn; my_FLVPlybk.forwardButton = forbtn; my_FLVPlybk.volumeBar = volbar; my_FLVPlybk.seekBar = seekbar; my_FLVPlybk.bufferingBar = bufbar;
The following steps create custom StopButton, PlayPauseButton, MuteButton, and SeekBar controls:
1 Drag the FLVPlayback component to the Stage, and give it an instance name of my_FLVPlybk. 2 Set the source parameter through the Component inspector to
http://www.helpexamples.com/flash/video/cuepoints.flv.
3 Set the Skin parameter to None. 4 Drag a StopButton, a PlayPauseButton, and a MuteButton to the Stage, and place them over the FLVPlayback
instance, stacking them vertically on the left. Give each button an instance name in the Property inspector (such as my_stopbttn, my_plypausbttn, and my_mutebttn).
5 In the Library panel, open the FLVPlayback Skins folder, and then open the SquareButton folder below it. 6 Select the SquareBgDown movie clip, and double-click it to open it on the Stage. 7 Right-click (Windows) or Control-click (Macintosh), select Select All from the menu, and delete the symbol. 8 Select the oval tool, draw an oval in the same location, and set the fill to blue (#0033FF). 9 In the Property inspector, set the width (W:) to 40 and the height (H:) to 20. Set the x-coordinate (X:) to 0.0 and
MuteOffIcon, and StopIcon). You can find these movie clips in the Library panel under FLV Playback Skins/Label Button/Assets, where Label is the name of the button, such as Play, Pause, and so on. Follow these steps for each one:
a Select the Select All option. b Change the color to red (#FF0000). c Scale to 300%. d Change the X: location of the content to 7.0 to alter the horizontal placement of the icon in every button state.
Note: By changing the location this way, you avoid opening every button state and moving the icon movie clip instance.
13 Click the blue Back arrow above the Timeline to return to Scene 1, Frame 1. 14 Drag a SeekBar component to the Stage, and place it in the lower-right corner of the FLVPlayback instance. 15 In the Library panel, double-click the SeekBar to open it on the Stage. 16 Scale it to 400%. 17 Select the outline, and set the color to red (#FF0000). 18 Double-click SeekBarProgress in the FLVPlayback Skins/Seek Bar folder, and set the color to yellow (#FFFF00).
19 Double-click SeekBarHandle in the FLVPlayback Skins/Seek Bar folder and set the color to red (#FF0000). 20 Click the blue Back arrow above the Timeline to return to Scene 1, Frame 1. 21 Select the SeekBar instance on the Stage, and give it an instance name of my_seekbar. 22 In the Actions panel on Frame 1 of the Timeline, add an import statement for the video classes, and assign the
button and seek bar names to the corresponding FLVPlayback properties, as shown in the following example:
import fl.video.*; my_FLVPlybk.stopButton = my_stopbttn; my_FLVPlybk.playPauseButton = my_plypausbttn; my_FLVPlybk.muteButton = my_mutebttn; my_FLVPlybk.seekBar = my_seekbar;
You can also have as many additional clips as you want beside the standard controls. The only requirement for these clips is that their library symbols have Export for ActionScript checked in the Linkage dialog box. The custom clips in the Layout layer can have any instance name, other than the reserved instance names listed above. An instance name is only needed to set ActionScript on the clips to determine the layout. The border_mc clip is special. If you set the FlvPlayback.skinAutoHide property to true, the skin shows when the mouse is over the border_mc clip. This is important for skins that appear outside the bounds of the video player. For information on the skinAutoHide property, see Modify skin behavior on page 159. In the Flash FLA files, border_mc is used for the chrome and for the border around the Forward and Back buttons. The border_mc clip is also the part of the skin that has its alpha and color changed by the skinBackgroundAlpha and skinBackgroundColor properties. To allow customizable color and alpha, the ActionScript in the skin FLA file must include the following:
border_mc.colorMe = true;
ActionScript and skin layout The following ActionScript code generally applies to all controls. Some controls have specific ActionScript that defines additional behavior, and that is explained in the section for that control. The initial ActionScript is a large section that specifies the class names for each state of each component. You can see all of these class names in the SkinOverAll.fla file. The code looks like this for the Pause and Play buttons, for example:
this.pauseButtonDisabledState = "fl.video.skin.PauseButtonDisabled"; this.pauseButtonDownState = "fl.video.skin.PauseButtonDown"; this.pauseButtonNormalState = "fl.video.skin.PauseButtonNormal"; this.pauseButtonOverState = "fl.video.skin.PauseButtonOver"; this.playButtonDisabledState = "fl.video.skin.PlayButtonDisabled"; this.playButtonDownState = "fl.video.skin.PlayButtonDown"; this.playButtonNormalState = "fl.video.skin.PlayButtonNormal"; this.playButtonOverState = "fl.video.skin.PlayButtonOver";
The class names do not have actual external class files; they are just specified in the Linkage dialog box for all the movie clips in the library. In the ActionScript 2.0 component, there were movie clips on Stage that were actually used at run time. In the ActionScript 3.0 component, those movie clips are still in the FLA file, but just to make editing convenient. Now, they are all in guide layers and are not exported. All of the skin assets in the library are set to export on the first frame and they are created dynamically with code like this, for example:
new fl.video.skin.PauseButtonDisabled();
Following that section is ActionScript code that defines the minimum width and height for the skin. The Select Skin dialog box shows these values and they are used at run time to prevent the skin from scaling below its minimum size. If you do not want to specify a minimum size, leave it as undefined or less than or equal to zero.
// minimum width and height of video recommended to use this skin, // leave as undefined or <= 0 if there is no minimum this.minWidth = 270; this.minHeight = 60;
Property
anchorLeft
Description Boolean. Positions the control relative to the left side of the FLVPlayback instance. Defaults to true unless anchorRight is explicitly set to true, and then it defaults to false. Boolean. Positions the control relative to the right side of the FLVPlayback instance. Defaults to false. Boolean. Positions the control relative to the bottom of the FLVPlayback instance. Defaults to true, unless anchorTop is explicitly set to true, and then it defaults to false. Boolean. Positions the control relative to the top of the FLVPlayback instance. Defaults to false.
anchorRight anchorBottom
anchorTop
If both the anchorLeft and anchorRight properties are true, the control is scaled horizontally at run time. If both the anchorTop and anchorBottom properties are true, the control is scaled vertically at run time. To see the effects of these properties, see how they are used in the Flash skins. The BufferingBar and SeekBar controls are the only ones that scale, and they are laid on top of one another and have both the anchorLeft and anchorRight properties set to true. All controls to the left of the BufferingBar and SeekBar have anchorLeft set to true, and all controls to their right have anchorRight set to true. All controls have anchorBottom set to true. You can try editing the movie clips on the Layout layer to make a skin where the controls sit at the top rather than at the bottom. You simply need to move the controls to the top, relative to video_mc, and set anchorTop equal to true for all controls.
Buffering bar
The buffering bar has two movie clips: bufferingBar_mc and bufferingBarFill_mc. Each clips position on the Stage relative to the other clip is important because this relative positioning is maintained. The buffering bar uses two separate clips because the component scales bufferingBar_mc but not bufferingBarFill_mc. The bufferingBar_mc clip has 9-slice scaling applied to it, so the borders wont distort when it scales. The bufferingBarFill_mc clip is extremely wide, so that it will always be wide enough without needing to be scaled. It is automatically masked at run time to show only the portion above the stretched bufferingBar_mc. By default, the exact dimensions of the mask will maintain an equal margin on the left and right within the bufferingBar_mc, based on the difference between the x (horizontal) positions of bufferingBar_mc and bufferingBarFill_mc. You can customize the positioning with ActionScript code. If your buffering bar does not need to scale or does not use 9-slice scaling, you could set it up like the FLV Playback Custom UI BufferingBar component. For more information, see BufferingBar component on page 151. The buffering bar has the following additional property:
Property
fill_mc:MovieClip
Description Specifies the instance name of the buffering bar fill. Defaults to bufferingBarFill_mc.
The seekBarProgress_mc clip works without a fill_mc, much like the way a progress_mc clip works in FLV Playback Custom UI components. In other words, it is not masked and is scaled horizontally. The exact dimensions of the seekBarProgress_mc at 100% are defined by left and right margins within the seekBarProgress_mc clip. These dimensions are, by default, equal and based on the difference between the x (horizontal) positions of seekBar_mc and seekBarProgress_mc. You can customize the dimensions with ActionScript in the seek bar movie clip, as shown in the following example:
this.seekBar_mc.progressLeftMargin = 2; this.seekBar_mc.progressRightMargin = 2; this.seekBar_mc.progressY = 11; this.seekBar_mc.fullnessLeftMargin = 2; this.seekBar_mc.fullnessRightMargin = 2; this.seekBar_mc.fullnessY = 11;
You can put this code either in the SeekBar movie clip Timeline or you could put it with the other ActionScript code on the main Timeline. If you customize with code instead of modifying the layout, the fill doesn't need to be on the Stage. It just needs to be in the library, set to export for ActionScript on Frame 1 with the correct class name. As with the FLV Playback Custom UI SeekBar component, it is possible to create a fullness movie clip for the seek bar. If your seek bar does not need to scale, or if it does scale but does not use 9-slice scaling, you could set up your progress_mc or fullness_mc using any of the methods used for FLV Playback Custom UI components. For more information, see . Because the volume bar in the Flash skins does not scale, it is constructed the same way as the VolumeBar FLV Playback Custom UI component. For more information, see SeekBar and VolumeBar components on page 151. The exception is that the handle is implemented differently. Seekbar and VolumeBar handles The SeekBar and VolumeBar handles are placed on the Layout layer next to the bar. By default, the handles left margin, right margin, and y-axis values are set by its position relative to the bar movie clip. The left margin is set by the difference between the handles x (horizontal) location and the bars x (horizontal) location, and the right margin is equal to the left margin. You can customize these values through ActionScript in the SeekBar or VolumeBar movie clip. The following example is the same ActionScript code that is used with the FLV Playback Custom UI components:
this.seekBar_mc.handleLeftMargin = 2; this.seekBar_mc.handleRightMargin = 2; this.seekBar_mc.handleY = 11;
You can put this code either in the SeekBar movie clip Timeline or you could put it with the other ActionScript code on the main Timeline. If you customize with code instead of modifying the layout, the handle doesnt need to be on the Stage. It just needs to be in the library, set to export for ActionScript on Frame 1 with the correct class name. Beyond these properties, the handles are simple movie clips, set up the same way as they are in the FLV Playback Custom UI components. Both have rectangle backgrounds with the alpha property set to 0. These are present only to increase the hit region and are not required.
The <head> tag may contain the <meta> and <layout> tags. The <meta> tag supports only the base attribute, which is used to specify the URL of the streaming video (RTMP from a FMS). The <layout> tag supports only the root-layout element, which is used to set the height and width attributes, and, therefore, determines the size of the window in which the FLV file is rendered. These attributes accept only pixel values, not percentages.
Within the body of the SMIL file, you can either include a single link to a FLV source file or, if youre streaming multiple files for multiple bandwidths from a FMS (as in the previous example), you can use the <switch> tag to list the source files. The video and ref tags within the <switch> tag are synonymousthey both can use the src attribute to specify FLV files. Further, each can use the region, system-bitrate, and dur attributes to specify the region, the minimum bandwidth required, and the duration of the FLV file. Within the <body> tag, only one occurrence of either the <video>, <src>, or <switch> tag is allowed. The following example shows a progressive download for a single FLV file that does not use bandwidth detection:
<smil> <head> <layout> <root-layout width="240" height="180" /> </layout> </head> <body> <video src=""myvideo.flv" /> </body> </smil>
<smil>
Availability Flash Professional 8. Usage
<smil> ... child tags ... </smil>
Parent tag None. Description Top-level tag, which identifies a SMIL file. Example The following example shows a SMIL file specifying three FLV files:
<smil> <head> <meta base="rtmp://myserver/myapp/" /> <layout> <root-layout width="240" height="180" /> </layout> </head> <body> <switch> <ref src="myvideo_cable.flv" dur="3:00.1"/> <video src="myvideo_isdn.flv" system-bitrate="128000" dur="3:00.1"/> <video src="myvideo_mdm.flv" system-bitrate="56000"dur="3:00.1"/> </switch> </body> </smil>
<head>
Availability Flash Professional 8. Usage
<head> ... child tags ... </head>
Parent tag
<smil>
Description Supporting the <meta> and <layout> tags, specifies the location and default layout (height and width) of the source FLV files. Example The following example sets the root layout to 240 pixels by 180 pixels:
<head> <meta base="rtmp://myserver/myapp/" /> <layout> <root-layout width="240" height="180" /> </layout> </head>
<meta>
Availability Flash Professional 8. Usage
<meta/>
Attributes
base
Child tags
<layout>
Parent tag None. Description Contains the base attribute which specifies the location (RTMP URL) of the source FLV files. Example The following example shows a meta tag for a base location on myserver:
<meta base="rtmp://myserver/myapp/" />
<layout>
Availability Flash Professional 8. Usage
<layout> ... child tags ... </layout>
Parent tag
<meta>
Example The following example specifies the layout of 240 pixels by 180 pixels:
<layout> <root-layout width="240" height="180" /> </layout>
<root-layout>
Availability Flash Professional 8. Usage
<root-layout...attributes.../>
Description Specifies the width and height of the FLV file. Example The following example specifies the layout of 240 pixels by 180 pixels:
<root-layout width="240" height="180" />
<body>
Availability Flash Professional 8. Usage
<body> ... child tags ... </body>
Attributes None.
Child tags
<video>, <ref>, <switch>
Parent tag
<smil>
Description Contains the <video>, <ref>, and <switch> tags, which specify the name of the source FLV file, the minimum bandwidth, and the duration of the FLV file. The system-bitrate attribute is supported only when using the <switch> tag. Within the <body> tag, only one instance of either the <switch>, <video>, or <ref> tag is allowed. Example The following example specifies three FLV files, two using the video tag, and one using the ref tag:
<body> <switch> <ref src="myvideo_cable.flv" dur="3:00.1"/> <video src="myvideo_isdn.flv" system-bitrate="128000" dur="3:00.1"/> <video src="myvideo_mdm.flv" system-bitrate="56000"dur="3:00.1"/> </switch> </body>
<video>
Availability Flash Professional 8. Usage
<video...attributes.../>
Attributes
src, system-bitrate, dur
Description Synonymous with the <ref> tag. Supports the src and dur attributes, which specify the name of the source FLV file and its duration. The dur attribute supports the full (00:03:00:01) and partial (03:00:01) time formats. Example The following example sets the source and duration for a video:
<video src="myvideo_mdm.flv" dur="3:00.1"/>
<ref>
Availability Flash Professional 8. Usage
<ref...attributes.../>
Attributes
src, system-bitrate, dur
Description Synonymous with <video> tag. Supports the src and dur attributes, which specify the name of the source FLV file and its duration. The dur attribute supports the full (00:03:00:01) and partial (03:00:01) time formats. Example The following example sets the source and duration for a video:
<ref src="myvideo_cable.flv" dur="3:00.1"/>
<switch>
Availability Flash Professional 8. Usage
<switch> ... child tags ... <switch/>
Parent tag
<body>
Description Used with either the <video> or <ref> child tag to list the FLV files for multiple bandwidth video streaming. The <switch> tag supports the system-bitrate attribute, which specifies the minimum bandwidth as well as the src and dur attributes. Example The following example specifies three FLV files, two using the video tag, and one using the ref tag:
<switch> <ref src="myvideo_cable.flv" dur="3:00.1"/> <video src="myvideo_isdn.flv" system-bitrate="128000" dur="3:00.1"/> <video src="myvideo_mdm.flv" system-bitrate="56000"dur="3:00.1" /> </switch>
167
instances.
Toggle Button Control Provide user interaction with captioning through a captioning toggle button.
component to which you want to add captioning. Note: Adobe provides two files to help you learn the FLVPlaybackCaptioning component quickly: caption_video.flv (a FLVPlayback sample) and caption_video.xml (a captioning sample). Access these files at www.helpexamples.com/flash/video/caption_video.flv and www.helpexamples.com/flash/video/caption_video.xml.
3 (Optional) Drag the CaptionButton component to the same stage as the FLVPlayback and FLVPlaybackCaptioning
components. The CaptionButton component enables a user to turn captioning on and off. Note: To enable the CaptionButton component, you must drag it to the same stage as the FLVPlayback and FLVPlaybackCaptioning components.
4 With the FLVPlaybackCaptioning component selected on the Stage, on the Parameters tab of the Property
Set showCaptions to true. Specify the source of the Timed Text XML file to download.
While working in Flash to test your captions, you should set the showCaptions property to true. However, if you include the CaptionButton component to allow users to turn captioning on and off, you should set the showCaptions property to false. Other parameters are available to help you customize the FLVPlaybackCaptioning component. For more information, see Customize the FLVPlaybackCaptioning component on page 176 and the ActionScript 3.0 Reference for Flash Professional.
5 Select Control > Test Movie to start the video.
Create an instance dynamically using ActionScript: 1 Drag the FLVPlayback component from the Component panel to the Library panel (Windows > Library).
2 Drag the FLVPlaybackCaptioning component from the Component panel to the Library panel. 3 Add the following code to the Actions panel on Frame 1 of the Timeline.
import fl.video.*; var my_FLVPlybk = new FLVPlayback(); my_FLVPlybk.x = 100; my_FLVPlybk.y = 100; addChild(my_FLVPlybk); my_FLVPlybk.skin = "install_drive:/Program Files/Adobe/Adobe Flash CS5/en/Configuration/FLVPlayback Skins/ActionScript 3.0/SkinUnderPlaySeekCaption.swf"; my_FLVPlybk.source = "http://www.helpexamples.com/flash/video/caption_video.flv"; var my_FLVPlybkcap = new FLVPlaybackCaptioning(); addChild (my_FLVPlybkcap); my_FLVPlybkcap.source = "http://www.helpexamples.com/flash/video/caption_video.xml"; my_FLVPlybkcap.showCaptions = true;
4 Change install_drive to the drive on which you installed Flash, and modify the path to reflect the location of the
Skins folder for your installation: Note: If you create an FLVPlayback instance with ActionScript, you must also assign a skin to it dynamically by setting the skin property with ActionScript. When you apply a skin with ActionScript, it is not automatically published with the SWF file. Copy the skin SWF file and the application SWF file to your server, or the skin SWF file wont be available when a user executes it.
default is true.
captionTargetName Identifies the TextField or MovieClip instance name containing captions. The default is auto. flvPlaybackName Identifies the FLVPlayback instance name that you want to caption. The default is auto.
simpleFormatting Limits formatting instructions of the Timed Text XML file when set to true. The default is false. showCaptions Determines if captions display. The default is true. source Identifies the location of the Timed Text XML file.
For more information on all of the FLVPlaybackCaptioning parameters, see the ActionScript 3.0 Reference for Flash Professional.
Display captions
To view captioning, set the showCaptions parameter to true. For more information on all of the FLVPlaybackCaptioning component parameters, see the ActionScript 3.0 Reference for Flash Professional. In the previous examples, you learned how to create and enable the FLVPlaybackCaptioning component to display captions. There are two sources you can use for your captions: (1) a Timed Text XML file containing your captions, or (2) an XML file with captioning text that you associate with embedded event cue points.
Set the size of the text with absolute pixel sizes or delta style (for example, +2, -4) Set the text color and font Make text bold and italic Set text justification Set the background color of the TextField for captions Set the background color of the TextField for captions to transparent (alpha 0) Set the word wrap of the TextField for captions (on or off)
The FLVPlaybackCaptioning component matches the time code of the FLV file. Every caption must have a begin attribute, which determines when the caption should appear. If the caption does not have a dur or end attribute, the caption disappears when the next caption appears, or when the FLV file ends.
The following is an example of a Timed Text XML file. This file (caption_video.xml) provides captioning for the caption_video.flv file. Access these files at www.helpexamples.com/flash/video/caption_video.flv and www.helpexamples.com/flash/video/caption_video.xml.
<?xml version="1.0" encoding="UTF-8"?> <tt xml:lang="en" xmlns="http://www.w3.org/2006/04/ttaf1"xmlns:tts="http://www.w3.org/2006/04/ttaf1#styling"> <head> <styling> <style id="1" tts:textAlign="right"/> <style id="2" tts:color="transparent"/> <style id="3" style="2" tts:backgroundColor="white"/> <style id="4" style="2 3" tts:fontSize="20"/> </styling> </head> <body> <div xml:lang="en"> <p begin="00:00:00.00" dur="00:00:03.07">I had just joined <span tts:fontFamily="monospaceSansSerif,proportionalSerif,TheOther"tts:fontSize="+2">Macromedia</ span> in 1996,</p> <p begin="00:00:03.07" dur="00:00:03.35">and we were trying to figure out what to do about the internet.</p> <p begin="00:00:06.42" dur="00:00:03.15">And the company was in dire straights at the time.</p> <p begin="00:00:09.57" dur="00:00:01.45">We were a CD-ROM authoring company,</p> <p begin="00:00:11.42" dur="00:00:02.00">and the CD-ROM business was going away.</p> <p begin="00:00:13.57" dur="00:00:02.50">One of the technologies I remember seeing was Flash.</p> <p begin="00:00:16.47" dur="00:00:02.00">At the time, it was called <span tts:fontWeight="bold" tts:color="#ccc333">FutureSplash</span>.</p> <p begin="00:00:18.50" dur="00:00:01.20">So this is where Flash got its start.</p> <p begin="00:00:20.10" dur="00:00:03.00">This is smart sketch running on the <span tts:fontStyle="italic">EU-pin computer</span>,</p> <p begin="00:00:23.52" dur="00:00:02.00">which was the first product that FutureWave did.</p> <p begin="00:00:25.52" dur="00:00:02.00">So our vision for this product was to</p> <p begin="00:00:27.52" dur="00:00:01.10">make drawing on the computer</p> <p begin="00:00:29.02" dur="00:00:01.30" style="1">as <span tts:color="#ccc333">easy</span> as drawing on paper.</p> </div> </body> </tt>
set
xml:lang
Function
Tag/Value xml:space
Example
layout
Ignored / including any region tags in a layout tag section All attributes and contents are ignored. Allowed in p tags only. Required for media time deployment of captions. Allowed in p tags only. Recommended. If not included, the caption ends with the FLV file or when another caption starts. Allowed in p tags only. Recommended. If not included, the caption ends with the FLV file or when another caption starts. Full clock format <p begin="3s">
dur attributes
end attributes
00:03:00.1
03:00.1 10
Partial clock format Offset times without units. Offset represents seconds. Not supported. Time formats that include frames or ticks are not supported.
00:03:00:05 00:03:00:05.1 30f 30t Body tag Content tag body div tag p tag span tag
Required / Support for only one body tag. Zero or more allowed. The first tag is used. Zero or more allowed. A logical container for a sequence of textual content units. No support for nested spans. Support for attribute style tags. Denotes an explicit line break. Reference one or more style elements. Can be used as a tag and as an attribute. As a tag, an ID attribute is required (the style can be reused in the document). Support for one or more style tags inside style tag. Specify a style property that defines the background color of a region. Alpha is ignored unless set to zero (alpha 0) to make the background transparent. The color format is #RRGGBBAA.
<body><div>...</div></body>
br tag Styling Tags (All style tags are used within the p tag) tts:background Color style
Function
Tag/Value tts:color
Usage/Description Specify a style property that defines the foreground color. Alpha not supported for any colors. Value transparent translates to black.
Example <style id="3" style="2" tts:backgroundColor="white"/> "transparent" = #00000000 "black"=#000000FF "silver"=#C0C0C0FF "grey"=#808080FF "white"=#FFFFFFFF "maroon"=#800000FF "red"=#FF0000FF "purple"=#800080FF "fuchsia"("magenta")= #FF00FFFF "green"=#008000FF "lime"=#00FF00FF "olive"=#808000FF "yellow"=#FFFF00FF "navy"=#000080FF "blue"=#0000FFFF "teal"=#008080FF "aqua"("cyan")=#00FFFFFF
tts:fontFamily
Specify a style property that defines the font "default" = _serif family. "monospace" = _typewriter "sansSerif" = _sans "serif" = _serif "monospaceSansSerif" =_typewriter "monospaceSerif" =_typewriter "proportionalSansSerif" = _sans
tts:fontSize
Specify a style property that defines the font size. Only the first (vertical) value is used if two are supplied. Percentage values and units are ignored. Support for absolute pixel (for example, 12) and relative style (for example +2) sizes. Specify a style property that defines the font "normal" style. "italic" "inherit"* * The default behavior; inherits the style from the enclosing tag.
tts: fontStyle
Function
Usage/Description
Example
Specify a style property that defines the font "normal" weight. "bold" "inherit"* * The default behavior; inherits the style from the enclosing tag.
tts: textAlign
Specify a style property that defines how inline areas are aligned within a containing block area.
"left" "right" "center" "start" (="left") "end" (="right") "inherit"* *Inherits the style from the enclosing tag. If no textAlign tag is set, the default is "left".
tts: wrapOption
Specify a style property that defines "wrap" whether or not automatic line wrapping (breaking) applies within the context of the "noWrap" affected element. This setting affects all "inherit"* paragraphs in the caption element. *Inherits the style from the enclosing tag. If no wrapOption tag is set, the default is "wrap".
tts: direction tts: display tts: displayAlign tts: dynamicFlow tts: extent tts: lineHeight tts: opacity tts: origin tts: overflow tts: padding tts: showBackground tts: textOutline tts: unicodeBidi tts: visibility tts: writingMode tts: zIndex
with the fl.video.caption.2.0. prefix and follow the prefix with a string. The string is a series of positive integers that increment each time to keep each name unique. The prefix includes the version number that also matches the FLVPlayback version number. For Adobe Flash CS4 and later, you must set the version number to 2.0.
time The time property is the time when the caption should display. type The type property is a string whose value is "event". parameters The parameters property is an array that supports the following name-and-value pairs:
text:String The HTML-formatted text for the caption. This text is passed to the TextField.htmlText property directly. The FLVPlaybackCaptioning component supports an optional text:n property, which supports the use of multiple language tracks. For more information, see Support multiple language tracks with embedded cue points on page 176. endTime:Number The time when the caption should disappear. If you do not specify this property, the FLVPlaybackCaptioning component assumes it is not a number (NaN), and the caption is displayed until the FLV file completes (the FLVPlayback instance dispatches the VideoEvent.COMPLETE event). Specify the endTime:Number property in seconds.
backgroundColor:uint This parameter sets the TextField.backgroundColor. This property is optional. backgroundColorAlpha:Boolean If the backgroundColor has an alpha of 0%, then the parameter sets
TextField.background = !backgroundColor. This property is optional. wrapOption:Boolean This parameter sets the TextField.wordWrap. This property is optional.
Add the event cue points (following the FLVPlaybackCaptioning standards), and encode the video. In Flash, drag an FLVPlayback component and an FLVPlaybackCaptioning component to the Stage. Set the FLVPlayback and FLVPlaybackCaptioning components source properties (the location of your FLV file
and the location of your XML file).
Publish.
The following sample imports XML into the encoder:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?> <FLVCoreCuePoints> <CuePoint> <Time>9136</Time> <Type>event</Type> <Name>fl.video.caption.2.0.index1</Name> <Parameters> <Parameter> <Name>text</Name> <Value><![CDATA[Captioning text for the first cue point]]></Value> </Parameter> </Parameters> </CuePoint> <CuePoint> <Time>19327</Time> <Type>event</Type> <Name>fl.video.caption.2.0.index2</Name> <Parameters> <Parameter> <Name>text</Name> <Value><![CDATA[Captioning text for the second cue point]]></Value> </Parameter> </Parameters> </CuePoint> <CuePoint> <Time>24247</Time> <Type>event</Type> <Name>fl.video.caption.2.0.index3</Name> <Parameters> <Parameter> <Name>text</Name> <Value><![CDATA[Captioning text for the third cue point]]></Value> </Parameter> </Parameters> </CuePoint> <CuePoint> <Time>36546</Time> <Type>event</Type> <Name>fl.video.caption.2.0.index4</Name> <Parameters> <Parameter> <Name>text</Name> <Value><![CDATA[Captioning text for the fourth cue point]]></Value> </Parameter> </Parameters> </CuePoint> </FLVCoreCuePoints>
The FLVPlaybackCaptioning component also supports multiple language tracks with embedded cue point. For more information, see Support multiple language tracks with embedded cue points on page 176.
relative path). Note: The code example sets the testVideoPath variable to the Flash video sample, caption_video.flv. Change this variable to the path of the captioning video component to which you are adding a caption button component.
5 In the following code example, set the testCaptioningPath:String variable to an appropriate Timed Text XML
Note: The code example sets the testCaptioningPath variable to the Timed Text XML file, caption_video.xml. Change this variable to the path of the Timed Text XML file that contains captions for your video.
6 Save the following code as FLVPlaybackCaptioningExample.as in the same directory as your FLA file. 7 Set the DocumentClass in the FLA file to FLVPlaybackCaptioningExample.
package { import import import import
public class FLVPlaybackCaptioningExample extends Sprite { private var testVideoPath:String = "http://www.helpexamples.com/flash/video/caption_video.flv"; private var testCaptioningPath:String = "http://www.helpexamples.com/flash/video/caption_video.xml"; public function FLVPlaybackCaptioningExample() { player.source = testVideoPath; player.skin = "SkinOverAllNoCaption.swf"; player.skinBackgroundColor = 0x666666; player.skinBackgroundAlpha = 0.5; captioning.flvPlayback = player; captioning.source = testCaptioningPath; captioning.autoLayout = false; captioning.addEventListener("captionChange",onCaptionChange); } private function onCaptionChange(e:*):void { var tf:* = e.target.captionTarget; var player:FLVPlayback = e.target.flvPlayback; // move the caption below the video tf.y = 210; } } }
For more information on all of the FLVPlaybackCaptioning parameters, see the ActionScript 3.0 Reference for Flash Professional.