® ™
Adobe Flex 2
Flex 2 Developer’sGuide
© 2006 Adobe Systems Incorporated. All rights reserved.
Flex™ 2 Developer’s Guide
If this guide is distributed with software that includes an end-user agreement, this guide, as well as the software described in it, is
furnished under license and may be used or copied only in accordance with the terms of such license. Except as permitted by any
such license, no part of this guide may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means,
electronic, mechanical, recording, or otherwise, without the prior written permission of Adobe Systems Incorporated. Please note
that the content in this guide is protected under copyright law even if it is not distributed with software that includes an end-user
license agreement.
The content of this guide is furnished for informational use only, is subject to change without notice, and should not be
construed as a commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability
for any errors or inaccuracies that may appear in the informational content contained in this guide.
Please remember that existing artwork or images that you may want to include in your project may be protected under copyright
law. The unauthorized incorporation of such material into your new work could be a violation of the rights of the copyright
owner. Please be sure to obtain any permission required from the copyright owner.
Any references to company names in sample templates are for demonstration purposes only and are not intended to refer to any
actual organization.
Adobe, the Adobe logo, Flex, Flex Builder and Flash Player are either registered trademarks or trademarks of Adobe Systems
Incorporated in the United States and/or other countries. ActiveX and Windows are either registered trademarks or trademarks of
Microsoft Corporation in the United States and/or other countries. Linux is a registered trademark of Linus Torvalds. Solaris is a
registered trademark or trademark of Sun Microsystems, Inc. in the United States and other countries. All other trademarks are
the property of their respective owners.
This product includes software developed by the Apache Software Foundation (http://www.apache.org/). Macromedia Flash 8
video is powered by On2 TrueMotion video technology. © 1992-2005 On2 Technologies, Inc. All Rights Reserved. http://
www.on2.com. This product includes software developed by the OpenSymphony Group (http://www.opensymphony.com/).
Portions licensed from Nellymoser (www.nellymoser.com). Portions utilize Microsoft Windows Media Technologies. Copyright
(c) 1999-2002 Microsoft Corporation. All Rights Reserved. Includes DVD creation technology used under license from Sonic
Solutions. Copyright 1996-2005 Sonic Solutions. All Rights Reserved. This Product includes code licensed from RSA Data
Security. Portions copyright Right Hemisphere, Inc. This product includes software developed by the OpenSymphony Group
(http://www.opensymphony.com/).
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 Systems Incorporated, 345 Park Avenue, San Jose, CA 95110-2704, USA. For U.S.
Government End Users, Adobe agrees to comply with all applicable equal opportunity laws including, if appropriate, the
provisions of Executive Order 11246, as amended, Section 402 of the Vietnam Era Veterans Readjustment Assistance Act of
1974 (38 USC 4212), and Section 503 of the Rehabilitation Act of 1973, as amended, and the regulations at 41 CFR Parts 60-1
through 60-60, 60-250 ,and 60-741. The affirmative action clause and regulations contained in the preceding sentence shall be
incorporated by reference.
Contents
Chapter 1: About Flex Documentation . . . . . . . . . . . . . . . . . . . . . . 15
PART 1: USING FLEX PROGRAMMING LANGUAGES
Chapter 2: Developing Applications in MXML . . . . . . . . . . . . . . . 21
About MXML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Developing applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Chapter 3: MXML Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Basic MXML syntax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Setting component properties. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Chapter 4: Using ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Using ActionScript in Flex applications. . . . . . . . . . . . . . . . . . . . . . . . . . 55
Working with Flex components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Comparing, including, and importing ActionScript code. . . . . . . . . . . 68
Techniques for separating ActionScript from MXML . . . . . . . . . . . . . .72
Creating ActionScript components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .75
Performing object introspection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Chapter 5: Using Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .83
About events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Using events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .87
Manually dispatching events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .109
Event propagation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Event priorities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Using event subclasses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
About keyboard events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .123
iii
PART 2: BUILDING USER INTERFACES FOR FLEX APPLICA-
TIONS
Chapter 6: Using Flex Visual Components . . . . . . . . . . . . . . . . . 133
About visual components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Class hierarchy for visual components . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Using the UIComponent class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Sizing visual components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .141
Handling events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Using styles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .151
Using behaviors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Applying skins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Changing the appearance of a component at run time . . . . . . . . . . . . 155
Extending components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Chapter 7: Using Data Providers and Collections. . . . . . . . . . . . 161
About data providers and collections . . . . . . . . . . . . . . . . . . . . . . . . . . . .161
Using IList interface methods and properties . . . . . . . . . . . . . . . . . . . . 174
Using ICollectionView interface methods and properties. . . . . . . . . . 176
Using events and update notifications . . . . . . . . . . . . . . . . . . . . . . . . . . 189
Using hierarchical data providers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Using remote data providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Chapter 8: Sizing and Positioning Components . . . . . . . . . . . . . 221
About sizing and positioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
Sizing components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .228
Positioning and laying out controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . .248
Using constraint-based layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .255
Chapter 9: Using Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
About controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
Working with controls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .266
Button control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .269
PopUpButton control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
ButtonBar and ToggleButtonBar controls . . . . . . . . . . . . . . . . . . . . . . 276
LinkBar control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
TabBar control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .283
CheckBox control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
RadioButton control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .288
NumericStepper control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
DateChooser and DateField controls . . . . . . . . . . . . . . . . . . . . . . . . . . .296
iv Contents
LinkButton control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
HSlider and VSlider controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .310
SWFLoader control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .319
Image control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
VideoDisplay control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
ColorPicker control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
Alert control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .351
ProgressBar control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
HRule and VRule controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .361
ScrollBar control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
Chapter 10: Using Text Controls . . . . . . . . . . . . . . . . . . . . . . . . . 369
About text controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
Using the text property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
Using the htmlText property. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
Selecting and modifying text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
Label control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
TextInput control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
Text control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
TextArea control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
RichTextEditor control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
Chapter 11: Using Menu-Based Controls . . . . . . . . . . . . . . . . . . 407
About menu-based controls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
Defining menu structure and data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
Handling menu-based control events . . . . . . . . . . . . . . . . . . . . . . . . . . .415
Menu control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
MenuBar control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .431
PopUpMenuButton control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
Chapter 12: Using Data-Driven Controls . . . . . . . . . . . . . . . . . . 439
List control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
HorizontalList control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
TileList control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
ComboBox control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
DataGrid control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
Tree control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
Chapter 13: Introducing Containers . . . . . . . . . . . . . . . . . . . . . . . 491
About containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .491
Using containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
Contents v
Using scroll bars. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .507
Using Flex coordinates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
Creating and managing component instances at run time . . . . . . . . . 516
Chapter 14: Using the Application Container . . . . . . . . . . . . . . 529
Using the Application container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
About the Application object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
Showing the download progress of an application . . . . . . . . . . . . . . 542
Chapter 15: Using Layout Containers. . . . . . . . . . . . . . . . . . . . . 553
About layout containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
Canvas layout container. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
Box, HBox, and VBox layout containers . . . . . . . . . . . . . . . . . . . . . . . 559
ControlBar layout container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .562
ApplicationControlBar layout container . . . . . . . . . . . . . . . . . . . . . . . . .564
DividedBox, HDividedBox, and VDividedBox layout containers . . . 567
Form, FormHeading, and FormItem layout containers . . . . . . . . . . . .570
Grid layout container. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594
Panel layout container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601
Tile layout container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
TitleWindow layout container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609
Chapter 16: Using Navigator Containers . . . . . . . . . . . . . . . . . . .627
About navigator containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
ViewStack navigator container. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .628
TabNavigator container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .634
Accordion navigator container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .639
PART 3: CUSTOMIZING THE USER INTERFACE
Chapter 17: Using Behaviors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649
About behaviors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649
Applying behaviors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659
Working with effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 674
Chapter 18: Using Styles and Themes . . . . . . . . . . . . . . . . . . . . .697
About styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .697
Using external style sheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 726
Using local style definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 727
Using the StyleManager class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .730
vi Contents
Using the setStyle() and getStyle() methods . . . . . . . . . . . . . . . . . . . . 737
Using inline styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 742
Loading style sheets at run time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 744
Using filters in Flex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753
About themes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756
Chapter 19: Using Fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 763
About fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 763
Using device fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 766
Using embedded fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 767
Using multiple typefaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 781
About the font managers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 786
Setting character ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 786
Embedding double-byte fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
Embedding fonts from SWF files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 791
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802
Chapter 20: Using Skins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
About skinning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
Graphical skinning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 807
Using SWF files as skins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .814
Programmatic skinning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .816
Creating themes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 849
Chapter 21: Using Item Renderers and Item Editors. . . . . . . . . . 851
About item renderers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .851
Creating an item renderer and item editor. . . . . . . . . . . . . . . . . . . . . . . 860
Creating drop-in item renderers and item editors . . . . . . . . . . . . . . . . 870
Creating inline item renderers and editors . . . . . . . . . . . . . . . . . . . . . . 875
Creating item renderers and item editor components . . . . . . . . . . . . 883
Working with item renderers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 892
Chapter 22: Working with Item Editors . . . . . . . . . . . . . . . . . . . 903
The cell editing process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 903
Creating an editable cell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 904
Returning data from an item editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 905
Sizing and positioning an item editor . . . . . . . . . . . . . . . . . . . . . . . . . . . 909
Making an item editor that responds to the Enter key . . . . . . . . . . . . . 911
Using the cell editing events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .912
Item editor examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 920
Examples using item editors with the list controls. . . . . . . . . . . . . . . . 934
Contents vii
Chapter 23: Using ToolTips. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 943
About ToolTips. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 943
Creating ToolTips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 944
Using the ToolTip Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 952
Using error tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .962
Chapter 24: Using the Cursor Manager. . . . . . . . . . . . . . . . . . . .967
About the Cursor Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .967
Using the Cursor Manager. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .968
Creating and removing a cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 969
Using a busy cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .970
Chapter 25: Localizing Flex Applications . . . . . . . . . . . . . . . . . 975
About localized Flex applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .975
Creating a localized application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .976
PART 4: FLEX PROGRAMMING TOPICS
Chapter 26: Dynamically Repeating Controls and Containers 995
About Repeater components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 995
Using the Repeater component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 996
Considerations when using a Repeater component . . . . . . . . . . . . . 1017
Chapter 27: Using View States . . . . . . . . . . . . . . . . . . . . . . . . . . 1019
About view states . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1019
Defining and applying view states . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1022
Building applications by using view states. . . . . . . . . . . . . . . . . . . . . .1045
Creating your own override classes. . . . . . . . . . . . . . . . . . . . . . . . . . . .1048
Chapter 28: Using Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . 1051
About transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1051
Defining transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1053
Handling events when using transitions . . . . . . . . . . . . . . . . . . . . . . . .1060
Using action effects in a transition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1061
Filtering effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1065
Transition tips and troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1077
Chapter 29: Using the Drag and Drop Manager . . . . . . . . . . . . 1081
About the Drag and Drop Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1081
Using drag-and-drop with list-based controls . . . . . . . . . . . . . . . . . . 1082
Manually adding drag-and-drop support . . . . . . . . . . . . . . . . . . . . . . .1090
Programming a drag-and-drop operation . . . . . . . . . . . . . . . . . . . . . .1098
viii Contents
Drag-and-drop techniques and considerations. . . . . . . . . . . . . . . . . . 1109
Chapter 30: Embedding Assets . . . . . . . . . . . . . . . . . . . . . . . . . .1113
About embedding assets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1113
Syntax for embedding assets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1116
Embedding asset types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1121
Chapter 31: Creating Modular Applications . . . . . . . . . . . . . . . . .1131
Modular applications overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1131
Creating modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1134
Compiling modules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1135
Loading and unloading modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1136
Using ModuleLoader events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1140
Chapter 32: Using the History Manager . . . . . . . . . . . . . . . . . . 1147
About history management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1148
Using standard history management . . . . . . . . . . . . . . . . . . . . . . . . . . . 1148
Using custom history management . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1150
How the HistoryManager class saves and loads states. . . . . . . . . . . 1156
Using history management in a custom wrapper . . . . . . . . . . . . . . . . 1157
Chapter 33: Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1161
About printing by using Flex classes . . . . . . . . . . . . . . . . . . . . . . . . . . . 1162
Using the FlexPrintJob class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1162
Using a print-specific output format . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1167
Printing multipage output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1171
Chapter 34: Communicating with the Wrapper . . . . . . . . . . . . .1181
About exchanging data with Flex applications. . . . . . . . . . . . . . . . . . . 1181
Passing request data to Flex applications. . . . . . . . . . . . . . . . . . . . . . . 1186
Accessing JavaScript functions from Flex . . . . . . . . . . . . . . . . . . . . . . 1192
Accessing Flex from JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1205
About ExternalInterface API security in Flex . . . . . . . . . . . . . . . . . . . . 1211
Chapter 35: Using Shared Objects . . . . . . . . . . . . . . . . . . . . . . . 1213
About shared objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1213
Creating a shared object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1215
Destroying shared objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1217
SharedObject example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1217
Contents ix
Chapter 36: Creating Accessible Applications . . . . . . . . . . . . . 1219
Accessibility overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1219
About screen reader technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1221
Configuring Flex applications for accessibility . . . . . . . . . . . . . . . . . . 1223
Accessible components and containers. . . . . . . . . . . . . . . . . . . . . . . . 1224
Creating tab order and reading order . . . . . . . . . . . . . . . . . . . . . . . . . . 1227
Creating accessibility with ActionScript . . . . . . . . . . . . . . . . . . . . . . . . 1232
Accessibility for hearing-impaired users. . . . . . . . . . . . . . . . . . . . . . . . 1233
Testing accessible content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1233
PART 5: FLEX DATA FEATURES
Chapter 37: Representing Data . . . . . . . . . . . . . . . . . . . . . . . . . 1237
About data representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1237
Chapter 38: Binding Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1245
About data binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1245
Binding data with curly braces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1247
Binding data with the <mx:Binding> tag. . . . . . . . . . . . . . . . . . . . . . . . . 1252
About the binding mechanism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1258
Using binding for moving related data . . . . . . . . . . . . . . . . . . . . . . . . . 1266
Chapter 39: Storing Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1269
About data models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1269
Defining a data model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1270
Specifying an external source for an <mx:Model> tag or <mx:XML> tag . .
1274
Using validators with a data model . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1276
Using a data model as a value object . . . . . . . . . . . . . . . . . . . . . . . . . . 1277
Binding data into an XML data model . . . . . . . . . . . . . . . . . . . . . . . . . 1279
Chapter 40: Validating Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1281
Validating data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1281
Using validators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1286
General guidelines for validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1303
Working with validation errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1306
Working with validation events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1310
Using standard validators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1313
x Contents
Chapter 41: Formatting Data . . . . . . . . . . . . . . . . . . . . . . . . . . . .1327
Using formatters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1327
Writing an error handler function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1329
Using the standard formatters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1331
PART 6: DATA ACCESS AND INTERCONNECTIVITY
Chapter 42: Accessing Server-Side Data . . . . . . . . . . . . . . . . 1345
About Flex data access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1345
About RPC services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1346
About the Data Management Service . . . . . . . . . . . . . . . . . . . . . . . . . 1348
About messaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1349
Using Flex Data Services with Flex Builder . . . . . . . . . . . . . . . . . . . . 1349
Chapter 43: Configuring Data Services . . . . . . . . . . . . . . . . . . . 1351
About service configuration files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1352
Configuring message channels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1360
Serializing data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1366
Securing destinations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1379
Configuring server-side service logging . . . . . . . . . . . . . . . . . . . . . . . 1384
Working with session data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1387
Using software clustering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1388
Managing services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1390
Using custom error handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1392
About Data Services class loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1394
Using the factory mechanism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1396
Chapter 44: Understanding RPC Components. . . . . . . . . . . . 1399
About RPC components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1399
Comparing the Flex RPC services feature to other technologies . 1403
Chapter 45: Using RPC Components. . . . . . . . . . . . . . . . . . . . .1407
Declaring an RPC component. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1407
Configuring a destination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1411
Calling a service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1413
Setting properties for RemoteObject methods or WebService opera-
tions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1424
Handling service results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1428
Using a service with binding, validation, and event listeners . . . . . 1438
Handling asynchronous calls to services . . . . . . . . . . . . . . . . . . . . . . 1439
Contents xi
Using features specific to RemoteObject components . . . . . . . . . . 1442
Using features specific to WebService components . . . . . . . . . . . . 1444
Chapter 46: Configuring RPC Services . . . . . . . . . . . . . . . . . . . 1451
Understanding destination configuration . . . . . . . . . . . . . . . . . . . . . . . 1451
Configuring destination properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1454
Configuring the Proxy Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1457
Chapter 47: Understanding Flex Messaging . . . . . . . . . . . . . . .1459
About messaging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1459
Understanding the Flex messaging architecture . . . . . . . . . . . . . . . . 1461
Chapter 48: Using Flex Messaging . . . . . . . . . . . . . . . . . . . . . .1465
Using messaging in a Flex application . . . . . . . . . . . . . . . . . . . . . . . . . 1465
Working with Producer components . . . . . . . . . . . . . . . . . . . . . . . . . . 1466
Working with Consumer components . . . . . . . . . . . . . . . . . . . . . . . . . 1472
Using subtopics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1476
Using a pair of Producer and Consumer components in an application .
1480
Chapter 49: Configuring the Message Service. . . . . . . . . . . . .1483
Understanding Message Service configuration . . . . . . . . . . . . . . . . . 1483
Configuring Message Service destinations . . . . . . . . . . . . . . . . . . . . . 1486
Creating a custom Message Service adapter . . . . . . . . . . . . . . . . . . .1494
Chapter 50: Understanding the Flex Data Management Service. .
1497
About the Data Management Service feature. . . . . . . . . . . . . . . . . . . 1497
Chapter 51: Distributing Data in Flex Applications . . . . . . . . . . 1501
Creating a distributed data application . . . . . . . . . . . . . . . . . . . . . . . . . 1501
Mapping client-side objects to Java objects . . . . . . . . . . . . . . . . . . . . 1510
Handling data synchronization conflicts. . . . . . . . . . . . . . . . . . . . . . . . 1514
Chapter 52: Configuring the Data Management Service . . . . 1517
About Data Management Service configuration . . . . . . . . . . . . . . . . 1518
Configuring Data Management Service destinations . . . . . . . . . . . .1520
Working with data adapters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1525
Managing hierarchical collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1556
Pushing data changes from the server to clients . . . . . . . . . . . . . . . . 1569
xii Contents
PART 7: CHARTING COMPONENTS
Chapter 53: Introduction to Charts. . . . . . . . . . . . . . . . . . . . . . .1573
About charting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1573
Using the charting controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1575
About the axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1583
About charting events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1584
Creating charts in ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1585
Defining chart data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1592
Chapter 54: Chart Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1623
Using area charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1624
Using bar charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1627
Using bubble charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1629
Using candlestick charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1631
Using column charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1635
Using HighLowOpenClose charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1642
Using line charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1646
Using pie charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1657
Using plot charts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1667
Using multiple data series. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1671
Using multiple axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1673
Chapter 55: Formatting Charts . . . . . . . . . . . . . . . . . . . . . . . . . . 1681
Applying chart styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1682
Adding ChartElement objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1690
Setting padding properties. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1693
Working with axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1698
Using strokes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1728
Using fills . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1735
Using filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1747
Adding grid lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1753
Using DataTips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1761
Skinning ChartItem objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1773
Using Legend controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1781
Stacking charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1793
Chapter 56: Using Events and Effects in Charts. . . . . . . . . . . . 1801
Handling user interactions with charts. . . . . . . . . . . . . . . . . . . . . . . . . . 1801
Using effects with charts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1819
Contents xiii
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i
xiv Contents
1
CHAPTER 1
About Flex Documentation
Flex 2 Developer’s Guide provides the tools for you to develop Internet applications by using
Adobe® Flex™ 2. This book is intended for application developers who are learning Flex or
want to extended their Flex programming knowledge. It provides a solid grounding in the
tools that Flex provides to develop applications.
Contents
Using this manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Accessing the Flex documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Using this manual
This manual can help anyone who is developing Flex applications. However, this manual is
most useful if you have basic experience using Flex, or have read Getting Started with Flex 2.
Getting Started with Flex 2 provides an introduction to Flex and helps you develop the basic
knowledge that makes using this manual easier.
Flex 2 Developer’s Guide is divided into the following parts:
Part Description
Part 1, “Using Flex Programming Describes how to use MXML and ActionScript.
Languages”
Part 2, “Building User Interfaces Describes how to use Flex components to build the user
for Flex Applications” interface to your application.
Part 3, “Customizing the User Describes how to improve the user experience by adding
Interface” additional functionality to your application.
Part 4, “Flex Programming Describes some advanced programming techniques that
Topics” you can use to make your applications more interactive
and expressive.
15
Part Description
Part 5, “Flex Data Features” Describes how to use Flex data representation and data
features.
Part 6, “Data Access and Describes the Flex features that let you work with
Interconnectivity” external data. Includes Adobe® Flex™ Data Services
features.
Part 7, “Charting Components” Describes how to use charting components.
Accessing the Flex documentation
The Flex documentation is designed to provide support for the complete spectrum of
participants.
Documentation set
The Flex documentation set includes the following titles:
Book Description
Flex 2 Developer’s Guide Describes how to develop your dynamic web
applications.
Getting Started with Flex 2 Contains an overview of Flex features and application
development procedures.
Building and Deploying Flex 2 Describes how to build and deploy Flex applications.
Applications
Creating and Extending Flex 2 Describes how to create and extend Flex components.
Components
Migrating Applications to Flex 2 Provides an overview of the migration process, as well as
detailed descriptions of changes in Flex and
ActionScript.
Using Flex Builder 2 Contains comprehensive information about all Adobe®
Flex™ Builder™ 2 features, for every level of Flex Builder
users.
Adobe Flex 2 Language Reference Provides descriptions, syntax, usage, and code
examples for the Flex API.
16 About Flex Documentation
Viewing online documentation
All Flex documentation is available online in HTML and Adobe® Portable Document Format
(PDF) files from the Adobe website. It is also available from the Adobe® Flex™ Builder™ Help
menu.
Typographical conventions
The following typographical conventions are used in this book:
■ Italic font indicates a value that should be replaced (for example, in a folder path).
■ Code font indicates code.
■ Code font italic indicates a parameter.
■ Boldface font indicates a verbatim entry.
Typographical conventions 17
18 About Flex Documentation
PART 1
Using Flex Programming
Languages 1
This part describes how to use MXML and ActionScript, the Adobe Flex 2
programming languages.
The following topics are included:
Chapter 2: Developing Applications in MXML . . . . . . . . . . . . . . . . 21
Chapter 3: MXML Syntax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Chapter 4: Using ActionScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55
Chapter 5: Using Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .83
19
CHAPTER 2
Developing Applications
in MXML
2
MXML is an XML language that you use to lay out user-interface components for Adobe Flex
applications. You also use MXML to declaratively define nonvisual aspects of an application,
such as access to server-side data sources and data bindings between user-interface
components and server-side data sources. This topic describes MXML and how you use
MXML to develop Flex applications.
For information on MXML syntax, see Chapter 3, “MXML Syntax,” on page 41.
Contents
About MXML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Developing applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
About MXML
You use two languages to write Flex applications: MXML and ActionScript. MXML is an
XML markup language that you use to lay out user-interface components. You also use
MXML to declaratively define nonvisual aspects of an application, such as access to data
sources on the server and data bindings between user-interface components and data sources
on the server.
Like HTML, MXML provides tags that define user interfaces. MXML will seem very familiar
if you have worked with HTML. However, MXML is more structured than HTML, and it
provides a much richer tag set. For example, MXML includes tags for visual components such
as data grids, trees, tab navigators, accordions, and menus, as well as nonvisual components
that provide web service connections, data binding, and animation effects. You can also
extend MXML with custom components that you reference as MXML tags.
One of the biggest differences between MXML and HTML is that MXML-defined
applications are compiled into SWF files and rendered by Adobe® Flash® Player, which
provides a richer and more dynamic user interface than page-based HTML applications
provide.
21
You can write an MXML application in a single file or in multiple files. MXML also supports
custom components written in MXML and ActionScript files.
Writing a simple application
Because MXML files are ordinary XML files, you have a wide choice of development
environments. You can write MXML code in a simple text editor, a dedicated XML editor, or
an integrated development environment (IDE) that supports text editing. Flex supplies a
dedicated IDE, called Adobe Flex Builder, that you can use to develop your applications.
The following example shows a simple “Hello World” application that contains just an
<mx:Application> tag and two child tags, the <mx:Panel> tag and the <mx:Label> tag. The
<mx:Application> tag defines the Application container that is always the root tag of a Flex
application. The <mx:Panel> tag defines a Panel container that includes a title bar, a title, a
status message, a border, and a content area for its children. The <mx:Label> tag represents a
Label control, a very simple user interface component that displays text.
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Panel title="My Application" paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10" >
<mx:Label text="Hello World!" fontWeight="bold" fontSize="24"/>
</mx:Panel>
</mx:Application>
Save this code to a file named hello.mxml. MXML filenames must end in a lowercase .mxml
file extension.
The following image shows the “Hello World” application rendered in a web browser
window:
22 Developing Applications in MXML
About XML encoding
The first line of the document specifies an optional declaration of the XML version. It is good
practice to include encoding information that specifies how the MXML file is encoded. Many
editors let you select from a range of file encoding options. On North American operating
systems, ISO-8859-1 is the dominant encoding format, and most programs use that format
by default. You can use the UTF-8 encoding format to ensure maximum platform
compatibility. UTF-8 provides a unique number for every character in a file, and it is
platform-, program-, and language-independent. If you specify an encoding format, it must
match the file encoding you use. The following example shows an XML declaration tag that
specifies the UTF-8 encoding format:
<?xml version="1.0" encoding="utf-8"?>
About the <mx:Application> tag
In addition to being the root tag of a Flex application, the <mx:Application> tag represents
an Application container. A container is a user-interface component that contains other
components and has built-in layout rules for positioning its child components. By default, an
Application container lays out its children vertically from top to bottom. You can nest other
types of containers inside an Application container, such as the Panel container shown above,
to position user-interface components according to other rules. For more information, see
Chapter 6, “Using Flex Visual Components,” on page 133.
About MXML tag properties
The properties of an MXML tag, such as the text, fontWeight, and fontSize properties of
the <mx:Label> tag, let you declaratively configure the initial state of the component. You
can use ActionScript code in an <mx:Script> tag to change the state of a component at run
time. For more information, see Chapter 4, “Using ActionScript,” on page 55.
Compiling MXML to SWF Files
You can deploy your application as a compiled SWF file or, if you have Adobe Flex Data
Services, you can deploy your application as a set of MXML and AS files.
If you are using Flex Builder, you compile and run the compiled SWF file from within Flex
Builder. After your application executes correctly, you deploy it by copying it to a directory on
your web server or application server. Users then access the deployed SWF file by making an
HTTP request in the form:
http://hostname/path/filename.swf
About MXML 23
The Flex also provides a command-line MXML compiler, mxmlc, that lets you compile
MXML files. You can use mxmlc to compile hello.mxml from a command line, as the
following example shows:
cd flexInstallDir/bin
mxmlc --show-actionscript-warnings=true --strict=true
c:/appDir/hello.mxml
In this example, flexInstallDir is the Flex installation directory, and appDir is the directory
containing hello.mxml. The resultant SWF file, hello.swf, is written to the same directory as
hello.mxml.
For more information about mxmlc, see Chapter 9, “Using the Flex Compilers,” in Building
and Deploying Flex 2 Applications. For more information about the debugger version of Flash
Player, see Chapter 11, “Logging,” in Building and Deploying Flex 2 Applications.
The relationship of MXML tags to ActionScript
classes
Adobe implemented Flex as an ActionScript class library. That class library contains
components (containers and controls), manager classes, data-service classes, and classes for all
other features. You develop applications by using the MXML and ActionScript languages with
the class library.
MXML tags correspond to ActionScript classes or properties of classes. Flex parses MXML
tags and compiles a SWF file that contains the corresponding ActionScript objects. For
example, Flex provides the ActionScript Button class that defines the Flex Button control. In
MXML, you create a Button control by using the following MXML statement:
<mx:Button label="Submit"/>
When you declare a control using an MXML tag, you create an instance object of that class.
This MXML statement creates a Button object, and initializes the label property of the
Button object to the string Submit.
An MXML tag that corresponds to an ActionScript class uses the same naming conventions as
the ActionScript class. Class names begin with an uppercase letter, and uppercase letters
separate the words in class names. Every MXML tag attribute corresponds to a property of the
ActionScript object, a style applied to the object, or an event listener for the object. For a
complete description of the Flex class library and MXML tag syntax, see the Adobe Flex 2
Language Reference.
24 Developing Applications in MXML
Understanding a Flex application structure
You can write an MXML application in a single file or in multiple files. You typically define a
main file that contains the <mx:Application> tag. From within your main file, you can then
reference additional files written in MXML, ActionScript, or a combination of the two
languages.
A common coding practice is to divide your Flex application into functional units, or
modules, where watch module performs a discrete task. In Flex, you can divide your
application into separate MXML files and ActionScript files, where each file corresponds to a
different module. By dividing your application into modules you provide many benefits,
including the following:
Ease of development Different developers or development groups can develop and debug
modules independently of each other.
Reusability You can reuse modules in different application so that you do not have to
duplicate your work.
Maintainability You can isolate and debug errors faster than you could if you application
was developed in a single file.
In Flex, a module corresponds to a custom component implement either in MXML or in
ActionScript. These custom components can reference other custom components. There is no
restriction on the level of nesting of component references in Flex. You define your
components as required by your application.
Developing applications
MXML development is based on the same iterative process used for other types of web
application files such as HTML, JavaServer Pages (JSP), Active Server Pages (ASP), and
ColdFusion Markup Language (CFML). Developing a useful Flex application is as easy as
opening your favorite text editor, typing some XML tags, saving the file, requesting the file’s
URL in a web browser, and then repeating the same process.
Flex also provides tools for code debugging; for more information, see Chapter 12, “Using the
Command-Line Debugger,” in Building and Deploying Flex 2 Applications.
Developing applications 25
Laying out a user interface using containers
In the Flex model-view design pattern, user interface components represent the view. The
MXML language supports two types of user interface components: controls and containers.
Controls are form elements, such as buttons, text fields, and list boxes. Containers are
rectangular regions of the screen that contain controls and other containers.
You use container components for laying out a user interface, and for controlling user
navigation through the application. Examples of layout containers include the HBox
container for laying out child components horizontally, the VBox container for laying out
child components vertically, and the Grid container for laying out child components in rows
and columns. Examples of navigator containers include the TabNavigator container for
creating tabbed panels, the Accordion navigator container for creating collapsible panels, and
the ViewStack navigator container for laying out panels on top of each other.
The Container class is the base class of all Flex container classes. Containers that extend the
Container class add their own functionality for laying out child components. Typical
properties of a container tag include id, width, and height. For more information about the
standard Flex containers, see Chapter 13, “Introducing Containers,” on page 491.
The following image shows an example Flex application that contains a List control on the left
side of the user interface and a TabNavigator container on the right side. Both controls are
enclosed in a Panel container:
Panel container
List control TabNavigator container
Use the following code to implement this application:
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Panel title="My Application" paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10">
<mx:HBox>
<!-- List with three items -->
<mx:List>
<mx:dataProvider>
26 Developing Applications in MXML
<mx:Array>
<mx:String>Item 1</mx:String>
<mx:String>Item 2</mx:String>
<mx:String>Item 3</mx:String>
</mx:Array>
</mx:dataProvider>
</mx:List>
<!-- First pane of TabNavigator -->
<mx:TabNavigator borderStyle="solid">
<mx:VBox label="Pane1" width="300" height="150">
<mx:TextArea text="Hello World"/>
<mx:Button label="Submit"/>
</mx:VBox>
<!-- Second pane of TabNavigator -->
<mx:VBox label="Pane2" width="300" height="150">
<!-- Stock view goes here -->
</mx:VBox>
</mx:TabNavigator>
</mx:HBox>
</mx:Panel>
</mx:Application>
The List control and TabNavigator container are laid out side by side because they are in an
HBox container. The controls in the TabNavigator container are laid out from top to bottom
because they are in a VBox container.
For more information about laying out user-interface components, see Chapter 6, “Using Flex
Visual Components,” on page 133.
Adding user interface controls
Flex includes a large selection of user interface components, such as Button, TextInput, and
ComboBox controls. After you define the layout and navigation of your application by using
container components, you add the user interface controls.
The following example contains an HBox (horizontal box) container with two child controls,
a TextInput control and a Button control. An HBox container lays out its children
horizontally.
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox>
<mx:TextInput id="myText"/>
<mx:Button click="storeZipInDatabase(myText.text)"/>
</mx:HBox>
Developing applications 27
</mx:Application>
Typical properties of a control tag include id, width, height, fontSize, color, event
listeners for events such as click and change, and effect triggers such as showEffect and
rollOverEffect. For information about the standard Flex controls, see Chapter 9, “Using
Controls,” on page 259.
Using the id property with MXML tags
With a few exceptions (see “MXML tag rules” on page 54), an MXML tag has an optional id
property, which must be unique within the MXML file. If a tag has an id property, you can
reference the corresponding object in ActionScript.
In the following example, results from a web service request are traced in the writeToLog
function:
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
...
<mx:VBox>
<mx:TextInput id="myText" text="Hello World!" />
<mx:Button id="mybutton" label="Get Weather" click="writeToLog();"/>
</mx:VBox>
<mx:Script>
<![CDATA[
private function writeToLog():void {
trace(myText.text);
}
]]>
</mx:Script>
</mx:Application>
This code causes the MXML compiler to autogenerate a public variable named myText that
contains a reference to that TextInput instance. This autogenerated variable lets you access the
component instance in ActionScript. You can explicitly refer to the TextInput control’s
instance with its id instance reference in any ActionScript class or script block. By referring to
a component’s instance, you can modify its properties and call its methods.
Because each id value in an MXML file is unique, all objects in a file are part of the same flat
namespace. You do not qualify an object by referencing its parent with dot notation, as in
myVBox.myText.text.
For more information, see “Referring to Flex components” on page 60.
28 Developing Applications in MXML
Using XML namespaces
In an XML document, tags are associated with a namespace. XML namespaces let you refer to
more than one set of XML tags in the same XML document. The xmlns property in an
MXML tag specifies an XML namespace. To use the default namespace, specify no prefix. To
use additional tags, specify a tag prefix and a namespace. For example, the xmlns property in
the following <mx:Application> tag indicates that tags in the MXML namespace use the
prefix mx:. The Universal Resource Identifier (URI) for the MXML namespace is http://
www.adobe.com/2006/mxml.
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
XML namespaces give you the ability to use custom tags that are not in the MXML
namespace. The following example shows an application that contains a custom tag called
CustomBox. The namespace value containers.boxes.* indicates that an MXML
component called CustomBox is in the containers/boxes directory.
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:MyComps="containers.boxes.*">
<mx:Panel title="My Application" paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10">
<MyComps:CustomBox/>
</mx:Panel>
</mx:Application>
The containers/boxes directory can be a subdirectory of the directory that contains the
application file, or it can be a subdirectory of one of the ActionScript source path directories
assigned in the flex-config.xml file. If copies of the same file exist in both places, Flex uses the
file in the application file directory. The prefix name is arbitrary, but it must be used as
declared.
When using a component contained in a SWC file, the package name and the namespace
must match, even though the SWC file is in the same directory as the MXML file that uses it.
A SWC file is an archive file for Flex components. SWC files make it easy to exchange
components among Flex developers. You need only exchange a single file, rather than the
MXML or ActionScript files and images and other resource files. Also, the SWF file inside a
SWC file is compiled, which means that the code is obfuscated from casual view. For more
information on SWC files, see Chapter 9, “Using the Flex Compilers,” in Building and
Deploying Flex 2 Applications.
Developing applications 29
Using MXML to trigger run-time code
Flex applications are driven by run-time events, such as when a user selects a Button control.
You can specify event listeners, which consist of code for handling run-time events, in the event
properties of MXML tags. For example, the <mx:Button> tag has a click event property in
which you can specify ActionScript code that executes when the Button control is clicked at
run time. You can specify simple event listener code directly in event properties. To use more
complex code, you can specify the name of an ActionScript function defined in an
<mx:Script> tag.
The following example shows an application that contains a Button control and a TextArea
control. The click property of the Button control contains a simple event listener that sets
the value of the TextArea control’s text property to the text Hello World.
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Panel title="My Application" paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10">
<mx:TextArea id="textarea1"/>
<mx:Button label="Submit" click="textarea1.text='Hello World';"/>
</mx:Panel>
</mx:Application>
The following image shows the application rendered in a web browser window:
The following example shows the code for a version of the application in which the event
listener is contained in an ActionScript function in an <mx:Script> tag:
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
private function hello():void {
textarea1.text="Hello World";
}
]]>
</mx:Script>
30 Developing Applications in MXML
<mx:Panel title="My Application" paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10" >
<mx:TextArea id="textarea1"/>
<mx:Button label="Submit" click="hello();"/>
</mx:Panel>
</mx:Application>
For more information about using ActionScript with MXML, see Chapter 4, “Using
ActionScript,” on page 55.
Binding data between components
Flex provides simple syntax for binding the properties of components to each other. In the
following example, the value inside the curly braces ({ }) binds the text property of a
TextArea control to the text property of a TextInput control. When the application
initializes, both controls display the text Hello. When the user clicks the Button control, both
controls display the text Goodbye.
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Panel title="My Application" paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10" >
<mx:TextInput id="textinput1" text="Hello"/>
<mx:TextArea id="textarea1" text="{textinput1.text}"/>
<mx:Button label="Submit" click="textinput1.text='Goodbye';"/>
</mx:Panel>
</mx:Application>
The following image shows the application rendered in a web browser window after the user
clicks the Submit button:
As an alternative to the curly braces ({ }) syntax, you can use the <mx:Binding> tag, in which
you specify the source and destination of a binding. For more information about data
binding, see Chapter 39, “Storing Data,” on page 1269.
Developing applications 31
Using RPC services
Remote-procedure-call (RPC) services let your application interact with remote servers to
provide data to your applications, or for your application to send data to a server.
Flex is designed to interact with several types of RPC services that provide access to local and
remote server-side logic. For example, a Flex application can connect to a web service that uses
the Simple Object Access Protocol (SOAP), a Java object residing on the same application
server as Flex using AMF, or an HTTP URL that returns XML. AMF is the protocol used in
Flash Remoting MX.
The MXML components that provide data access are called RPC components. MXML
includes the following types of RPC components:
■ WebService provides access to SOAP-based web services
■ HTTPService provides access to HTTP URLs that return data
■ RemoteObject provides access to Java objects using the AMF protocol (Flex Data Services
only)
The following example shows an application that calls a web service that provides weather
information, and displays the current temperature for a given ZIP code. The application
binds the ZIP code that a user enters in a TextInput control to a web service input parameter.
It binds the current temperature value contained in the web service result to a TextArea
control.
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<!-- Define the web service connection
(the specified WSDL URL is not functional). -->
<mx:WebService id="WeatherService"
wsdl="http:/example.com/ws/WeatherService?wsdl"
useProxy="false">
<!-- Bind the value of the ZIP code entered in the TextInput control
to the ZipCode parameter of the GetWeather operation. -->
<mx:operation name="GetWeather">
<mx:request>
<ZipCode>{zip.text}</ZipCode>
</mx:request>
</mx:operation>
</mx:WebService>
<mx:Panel title="My Application" paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10" >
<!-- Provide a ZIP code in a TextInput control. -->
<mx:TextInput id="zip" width="200" text="Zipcode please?"/>
32 Developing Applications in MXML
<!-- Call the web service operation with a Button click. -->
<mx:Button width="60" label="Get Weather"
click="WeatherService.GetWeather.send();"/>
<!-- Display the location for the specified ZIP code. -->
<mx:Label text="Location:"/>
<mx:TextArea text="{WeatherService.GetWeather.lastResult.Location}"/>
<!-- Display the current temperature for the specified ZIP code. -->
<mx:Label text="Temperature:"/>
<mx:TextArea
text="{WeatherService.GetWeather.lastResult.CurrentTemp}"/>
</mx:Panel>
</mx:Application>
The following image shows the application rendered in a web browser window:
For more information about using RPC services, see Chapter 44, “Understanding RPC
Components,” on page 1399.
Storing data in a data model
You can use a data model to store application-specific data. A data model is an ActionScript
object that provides properties for storing data, and optionally contains methods for
additional functionality. Data models provide a way to store data in the Flex application
before it is sent to the server, or to store data sent from the server before using it in the
application.
Developing applications 33
You can declare a simple data model that does not require methods in an <mx:Model>,
<mx:XML>, or <mx:XMLList> tag. The following example shows an application that contains
TextInput controls for entering personal contact information and a data model, represented
by the <mx:Model> tag, for storing the contact information:
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<!-- A data model called "contact" stores contact information.
The text property of each TextInput control shown above
is passed to a field of the data model. -->
<mx:Model id="contact">
<info>
<homePhone>{homePhoneInput.text}</homePhone>
<cellPhone>{cellPhoneInput.text}</cellPhone>
<email>{emailInput.text}</email>
</info>
</mx:Model>
<mx:Panel title="My Application" paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10" >
<!-- The user enters contact information in TextInput controls. -->
<mx:TextInput id="homePhoneInput"
text="This isn't a valid phone number."/>
<mx:TextInput id="cellPhoneInput" text="(999)999-999"/>
<mx:TextInput id="emailInput" text="
[email protected]"/>
</mx:Panel>
</mx:Application>
Validating data
You can use validator components to validate data stored in a data model, or in a Flex user-
interface component. Flex includes a set of standard validator components. You can also
create your own.
The following example uses validator components for validating that the expected type of data
is entered in the TextInput fields. Validation is triggered automatically when the users edits a
TextInput control. If validation fails, the user receives immediate visual feedback.
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<!-- A data model called "contact" stores contact information.
The text property of each TextInput control shown above
is passed to a field of the data model. -->
<mx:Model id="contact">
<info>
34 Developing Applications in MXML
<homePhone>{homePhoneInput.text}</homePhone>
<cellPhone>{cellPhoneInput.text}</cellPhone>
<email>{emailInput.text}</email>
</info>
</mx:Model>
<!-- Validator components validate data entered into the TextInput
controls. -->
<mx:PhoneNumberValidator id="pnV"
source="{homePhoneInput}" property="text"/>
<mx:PhoneNumberValidator id="pnV2"
source="{cellPhoneInput}" property="text"/>
<mx:EmailValidator id="emV" source="{emailInput}" property="text" />
<mx:Panel title="My Application" paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10" >
<!-- The user enters contact information in TextInput controls. -->
<mx:TextInput id="homePhoneInput"
text="This isn't a valid phone number."/>
<mx:TextInput id="cellPhoneInput" text="(999)999-999"/>
<mx:TextInput id="emailInput" text="
[email protected]"/>
</mx:Panel>
</mx:Application>
The following image shows the application rendered in a web browser window:
For more information about using data models, see Chapter 39, “Storing Data,” on
page 1269. For more information on validators, see Chapter 40, “Validating Data,” on
page 1281.
Formatting data
Formatter components are ActionScript components that perform a one-way conversion of
raw data to a formatted string. They are triggered just before data is displayed in a text field.
Flex includes a set of standard formatters. You can also create your own formatters. The
following example shows an application that uses the standard ZipCodeFormatter component
to format the value of a variable:
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
Developing applications 35
<!-- Declare a ZipCodeFormatter and define parameters. -->
<mx:ZipCodeFormatter id="ZipCodeDisplay" formatString="#####-####" />
<mx:Script>
<![CDATA[
private var storedZipCode:Number=123456789;
]]>
</mx:Script>
<mx:Panel title="My Application" paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10" >
<!-- Trigger the formatter while populating a string with data. -->
<mx:TextInput text="{ZipCodeDisplay.format(storedZipCode)}" />
</mx:Panel>
</mx:Application>
The following image shows the application rendered in a web browser window:
For more information about formatter components, see Chapter 41, “Formatting Data,” on
page 1327.
Using Cascading Style Sheets (CSS)
You can use style sheets based on the Cascading Style Sheets (CSS) standard to declare styles
to Flex components. The MXML <mx:Style> tag contains inline style definitions or a
reference to an external file that contains style definitions.
The <mx:Style> tag must be an immediate child of the root tag of the MXML file. You can
apply styles to an individual component using a class selector, or to all components of a
certain type using a type selector.
The following example defines a class selector and a type selector in the <mx:Style> tag. Both
the class selector and the type selector are applied to the Button control:
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Style>
.myClass { color: Red } /* class selector */
Button { font-size: 18pt} /* type selector */
</mx:Style>
36 Developing Applications in MXML
<mx:Panel title="My Application" paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10" >
<mx:Button styleName="myClass" label="This is red 18 point text."/>
</mx:Panel>
</mx:Application>
A class selector in a style definition, defined as a label preceded by a period, defines a new
named style, such as myClass in the preceding example. After you define it, you can apply the
style to any component using the styleName property. In the preceding example, you apply
the style to the Button control to set the font color to red.
A type selector applies a style to all instances of a particular component type. In the preceding
example, you set the font size for all Button controls to 18 points.
The following image shows the application rendered in a web browser window:
For more information about using Cascading Style Sheets, see Chapter 18, “Using Styles and
Themes,” on page 697.
Using skins
Skinning is the process of changing the appearance of a component by modifying or replacing
its graphical elements. These graphical elements can be made up of images or the output of
drawing API methods. They are known as symbols. You can reskin Flex components without
changing their functionality. A file that contains new skins for use in your Flex applications is
known as a theme.
There are two types of skins in Flex: graphical and programmatic. Graphical skins are Adobe
Flash symbols that you can change directly in the Macromedia® Flash® Professional 8 from
Adobe® authoring environment. You draw programmatic skins by using ActionScript
statements and define these skins in class files. Sometimes it is more advantageous to reskin a
component graphically, and in some cases it makes more sense to reskin a component
programmatically. You cannot combine graphical and programmatic skins in a single theme
file.
For more information about using skins, see Chapter 20, “Using Skins,” on page 805.
Developing applications 37
Using effects
An effect is a change to a component that occurs over a brief period of time. Examples of
effects are fading, resizing, and moving a component. An effect is combined with a trigger,
such as a mouse click on a component, a component getting focus, or a component becoming
visible, to form a behavior. In MXML, you apply effects as properties of a control or container.
Flex provides a set of built-in effects with default properties.
The following example shows an application that contains a Button control with its
rollOverEffect property set to use the WipeLeft effect when the user moves the mouse over
it:
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<!-- Define the effect. -->
<mx:WipeLeft id="myWL" duration="1000"/>
<mx:Panel title="My Application" paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10" >
<!-- Assign effect to targets. -->
<mx:Button id="myButton" rollOverEffect="{myWL}"/>
</mx:Panel>
</mx:Application>
For more information about effects, see Chapter 17, “Using Behaviors,” on page 649.
Defining custom MXML components
Custom MXML components are MXML files that you create and use as custom MXML tags
in other MXML files. They encapsulate and extend the functionality of existing Flex
components. Just like MXML application files, MXML component files can contain a mix of
MXML tags and ActionScript code. The name of the MXML file becomes the class name
with which you refer to the component in another MXML file.
You cannot access custom MXML component URLs directly in a web browser.
N O TE
The following example shows a custom ComboBox control that is prepopulated with list
items:
<?xml version="1.0"?>
<!-- MyComboBox.mxml -->
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:ComboBox >
38 Developing Applications in MXML
<mx:dataProvider>
<mx:String>Dogs</mx:String>
<mx:String>Cats</mx:String>
<mx:String>Mice</mx:String>
</mx:dataProvider>
</mx:ComboBox>
</mx:VBox>
The following example shows an application that uses the MyComboBox component as a
custom tag. The value * assigns the local namespace to the current directory.
<?xml version="1.0"?>
<!-- MyApplication.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:MyComps="containers.boxes.*">
<mx:Panel title="My Application" paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10" >
<MyComps:MyComboBox/>
</mx:Panel>
</mx:Application>
The following image shows the application rendered in a web browser window:
For more information about MXML components, see Chapter 7, “Creating Simple MXML
Components,” in Creating and Extending Flex 2 Components.
You can also define custom Flex components in ActionScript. For more information, see
Chapter 9, “Creating Simple Visual Components in ActionScript,” in Creating and Extending
Flex 2 Components.
Developing applications 39
40 Developing Applications in MXML
3
CHAPTER 3
MXML Syntax
MXML is an XML language that you use to lay out user-interface components for Adobe Flex
applications. This topic describes basic MXML syntax.
Contents
Basic MXML syntax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Setting component properties. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Basic MXML syntax
Most MXML tags correspond to ActionScript 3.0 classes or properties of classes. Flex parses
MXML tags and compiles a SWF file that contains the corresponding ActionScript objects.
ActionScript 3.0 uses syntax based on the ECMAScript edition 4 draft language specification.
ActionScript 3.0 includes the following features:
■ Formal class definition syntax
■ Formal packages structure
■ Typing of variables, parameters, and return values (compile-time only)
■ Implicit getters and setters that use the get and set keywords
■ Inheritance
■ Public and private members
■ Static members
■ Cast operator
For more information about ActionScript 3.0, see Chapter 7, “Using ActionScript,” on
page 91.
41
Naming MXML files
MXML filenames must adhere to the following naming conventions:
■ Filenames must be valid ActionScript identifiers, which means they must start with a
letter or underscore character (_), and they can only contain letters and numbers and
underscore characters after that.
■ Filenames must not be the same as ActionScript class names, component id values, or the
word application. Do not use filenames that match the names of MXML tags that are in
the mx namespace.
■ Filenames must end with a lowercase .mxml file extension.
Using tags that represent ActionScript classes
An MXML tag that corresponds to an ActionScript class uses the same naming conventions as
the ActionScript class. Class names begin with a capital letter, and capital letters separate the
words in class names. For example, when a tag corresponds to an ActionScript class, its
properties correspond to the properties and events of that class.
Setting component properties
In MXML, a component property uses the same naming conventions as the corresponding
ActionScript property. A property names begins with a lowercase letter, and capital letters
separate words in the property names.
You can set most component properties as tag attributes, in the form:
<mx:Label width="50" height="25" text="Hello World"/>
You can set all component properties as child tags, in the form:
<mx:Label>
<mx:width>50</mx:width>
<mx:height>25</mx:height>
<mx:text>Hello World</mx:text>
</mx:Label>
You often use child tags when setting the value of a property to a complex Object because it is
not possible to specify a complex Object as the value of tag attribute. In the following
example, you use child tags to set the data provider of a ComboBox control of an
ArrayCollection object:
<mx:ComboBox>
<mx:dataProvider>
<mx:ArrayCollection>
<mx:String>AK</mx:String>
42 MXML Syntax
<mx:String>AL</mx:String>
<mx:String>AR</mx:String>
</mx:ArrayCollection>
<mx:dataProvider>
</mx:ComboBox>
The one restriction on setting properties that use child tags is that the namespace prefix of a
child tag, mx: in the previous example, must match the namespace prefix of the component
tag.
Each of a component’s properties is one of the following types:
■ Scalar properties, such as a number or string
■ Array of scalar values, such as an array of numbers or strings
■ ActionScript object
■ Array of ActionScript objects
■ ActionScript properties
■ XML data
Adobe recommends that you assign scalar values using tag attributes, and that you assign
complex types, such as ActionScript objects, by using child tags.
Setting scalar properties
You usually specify the value of a scalar property as a property of a component tag, as the
following example shows:
<mx:Label width="50" height="25" text="Hello World"/>
Setting properties using constants
The valid values of many component properties are defined by static constants, where these
static constants are defined in an ActionScript class. In MXML, you can either use the static
constant to set the property value, or use the value of the static constant, as the following
example shows:
<!-- Set the property using the static constant. -->
<mx:HBox width="200" horizontalScrollPolicy="{ScrollPolicy.OFF}">
...
</mx:HBox>
<!-- Set the property using the value of the static constant. -->
<mx:HBox width="200" horizontalScrollPolicy="off">
...
</mx:HBox>
Setting component properties 43
The HBox container defines a property named horizontalScrollPolicy which defines the
operation of the container’s horizontal scroll bar. In this example, you explicitly set the
horizontalScrollPolicy property to disable the horizontal scroll bar.
In the first example, you set the horizontalScrollPolicy property using a static constant
named OFF, which is defined in the ScrollPolicy class. In MXML, you must use data binding
syntax when setting a property value to a static constant. The advantage of using the static
constant is that the Flex compiler recognizes incorrect property values, and issues an error
message at compile time.
Alternatively, you can set the value of the horizontalScrollPolicy property to the value of
the static constant. The value of the OFF static constant is "off". When you use the value of
the static constant to set the property value, the Flex compiler cannot determine if you used
an unsupported value. If you incorrectly set the property, you will not know until you get a
run-time error.
In ActionScript, you should always use static constants to set property values, as the following
example shows:
var myHBox:HBox = new HBox();
myHBox.horizontalScrollPolicy=ScrollPolicy.OFF;
Setting the default property
Many Flex components define a single default property. The default property is the MXML tag
property that is implicit for content inside of the MXML tag if you do not explicitly specify a
property. For example, consider the following MXML tag definition:
<mx:SomeTag>
anything here
</mx:SomeTag>
If this tag defines a default property named default_property, the preceding tag definition
is equivalent to the following code:
<mx:SomeTag>
<default_property>
anything here
</default_property>
</mx:SomeTag>
It is also equivalent to the following code:
<mx:SomeTag default_property="anything here"/>
44 MXML Syntax
The default property provides a shorthand mechanism for setting a single property. For a
ComboBox, the default property is the dataProvider property. Therefore the two
ComboBox definitions in the following code are equivalent:
<?xml version="1.0"?>
<!-- mxml\DefProp.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
<!-- Omit the default property. -->
<mx:ComboBox>
<mx:ArrayCollection>
<mx:String>AK</mx:String>
<mx:String>AL</mx:String>
<mx:String>AR</mx:String>
</mx:ArrayCollection>
</mx:ComboBox>
<!-- Explicitly speficy the default property. -->
<mx:ComboBox>
<mx:dataProvider>
<mx:ArrayCollection>
<mx:String>AK</mx:String>
<mx:String>AL</mx:String>
<mx:String>AR</mx:String>
</mx:ArrayCollection>
</mx:dataProvider>
</mx:ComboBox>
</mx:Application>
Not all Flex components define a default property. See Adobe Flex 2 Language Reference for
each component to determine its default property.
You can also define a default property when you create a custom component. For more
information, see Chapter 5, “Using Metadata Tags in Custom Components,” in Creating and
Extending Flex 2 Components.
Escaping characters using the backslash character
When setting a property value in MXML, you can escape a reserved character by prefixing it
with the backslash character, “\”, as the following example shows:
<?xml version="1.0"?>
<!-- mxml\EscapeChar.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
<mx:Label text="\{\}"/>
</mx:Application>
Setting component properties 45
In this example, you want to use literal curly brace characters ({ }) in a text string. But Flex
uses curly braces to indicate a data binding operation. Therefore, you prefix each curly brace
with the backslash character to cause the MXML compiler to interpret them as literal
characters.
Setting String properties using the backslash
character
The MXML compiler automatically escapes the backslash character in MXML when the
character is part of the value specified to a property of type String. Therefore, it always
converts "\" to "\\".
This is necessary because the ActionScript compiler recognizes "\\" as the character sequence
for a literal "\" character, and strips out the leading backslash when it initializes the property
value.
Do not use the backslash character (\) as a separator in the path to an application asset.
N OT E
You should always use a forward slash character (/) as the separator.
Including a newline character in a String value
For properties of type String, you can insert a newline character in the String in two ways:
■ By inserting the code in your String value in MXML
■ By inserting "\n" in an ActionScript String variable used to initialize the MXML property
To use the code to insert a newline character, include that code in the property value in
MXML, as the following example shows:
<mx:TextArea width="100%" text="Display Content"/>
To use an ActionScript String variable to insert a newline character, create an ActionScript
variable, and then use data binding to set the property in MXML, as the following example
shows:
<mx:Script>
<![CDATA[
[Bindable]
public var myText:String = "Display" + "\n" + "Content";
]]>
</mx:Script>
<mx:TextArea width="100%" text="{myText}"/>
In this example, you set the text property of the TextArea control to a value that includes a
newline character.
46 MXML Syntax
Notice that this example includes the [Bindable] metadata tag before the property
definition. This metadata tag specifies that the myText property can be used as the source of a
data binding expression. Data binding automatically copies the value of a source property of
one object to the destination property of another object at run time when the source
property changes.
If you omit this metadata tag, the compiler issues a warning message specifying that the
property cannot be used as the source for data binding. For more information, see Chapter
38, “Binding Data,” on page 1245.
Setting Arrays of scalar values
When a class has a property that takes an Array as its value, you can represent the property in
MXML using child tags. The component in the following example has a dataProvider
property that contains an Array of numbers:
<mx:List width="150">
<mx:dataProvider>
<mx:Array>
<mx:Number>94062</mx:Number>
<mx:Number>14850</mx:Number>
<mx:Number>53402</mx:Number>
</mx:Array>
</mx:dataProvider>
</mx:List>
The <mx:Array> and </mx:Array> tags around the Array elements are optional. Therefore,
you can also write this example as the following example shows:
<mx:List width="150">
<mx:dataProvider>
<mx:Number>94062</mx:Number>
<mx:Number>14850</mx:Number>
<mx:Number>53402</mx:Number>
</mx:dataProvider>
</mx:List>
In this example, since the data type of the dataProvider property is defined as Array, Flex
automatically converts the three number definitions into a three-element array.
Component developers may have specified additional information within the component
definition that defines the data type of the Array elements. For example, if the developer
specified that the dataProvider property only supports String elements, then this example
would cause a compiler error because you specified numbers to it. The Adobe Flex 2 Language
Reference documents the Array properties that define a required data type for the Array
elements.
Setting component properties 47
Setting Object properties
When a component has a property that takes an object as its value, you can represent the
property in MXML using a child tag with tag attributes, as the following example shows:
<mynamespace:MyComponent>
<mynamespace:nameOfProperty>
<mynamespace:typeOfObject prop1="val1" prop2="val2"/>
</mynamespace:nameOfProperty>
</mynamespace:MyComponent>
The following example shows an ActionScript class that defines an Address object. This object
is used as a property of the PurchaseOrder component in the next example.
class Address
{
public var name:String;
public var street:String;
public var city:String;
public var state:String;
public var zip:Number;
}
The following example shows an ActionScript class that defines a PurchaseOrder component
that has a property type of Address:
import example.Address;
class PurchaseOrder {
public var shippingAddress:Address;
public var quantity:Number;
...
}
In MXML, you define the PurchaseOrder component as the following example shows:
<mynamespace:PurchaseOrder quantity="3" xmlns:e="example">
<mynamespace:shippingAddress>
<mynamespace:Address name="Fred" street="123 Elm St."/>
</mynamespace:shippingAddress>
</mynamespace:PurchaseOrder>
If the value of the shippingAddress property is a subclass of Address (such as
DomesticAddress), you can declare the property value, as the following example shows:
<mynamespace:PurchaseOrder quantity="3" xmlns:e="example">
<mynamespace:shippingAddress>
<mynamespace:DomesticAddress name="Fred" street="123 Elm St."/>
</mynamespace:shippingAddress>
</mynamespace:PurchaseOrder>
If the property is explicitly typed as Object like the value property in the following example,
you can specify an anonymous object using the <mx:Object> tag.
48 MXML Syntax
class ObjectHolder {
public var value:Object
}
The following example shows how you specify an anonymous object as the value of the value
property:
<mynamespace:ObjectHolder>
<mynamespace:value>
<mx:Object foo='bar' />
</mynamespace:value>
</mynamespace:ObjectHolder>
Populating an Object with an Array
When a component has a property of type Object that takes an Array as its value, you can
represent the property in MXML using child tags, as the following example shows:
<mynamespace:MyComponent>
<mynamespace:nameOfObjectProperty>
<mx:Array>
<mx:Number>94062</mx:Number>
<mx:Number>14850</mx:Number>
<mx:Number>53402</mx:Number>
</mx:Array>
</mynamespace:nameOfObjectProperty>
</mynamespace:MyComponent>
In this example, you initialize the Object to a three element array of numbers.
As described in the section “Setting Arrays of scalar values” on page 47, the <mx:Array> tag
and the </mx:Array> tag around the Array elements are optional and may be omitted, as the
following example shows:
<mynamespace:MyComponent>
<mynamespace:nameOfObjectProperty>
<mx:Number>94062</mx:Number>
<mx:Number>14850</mx:Number>
<mx:Number>53402</mx:Number>
</mynamespace:nameOfObjectProperty>
</mynamespace:MyComponent>
The only exception to this rule is when you specify a single Array element for the Object
property. In that case, Flex does not create an Object containing a single-element array, but
instead creates an object and sets it to the specified value. This is a difference between the
following:
object=[element] // Object containing a one-element array
object=element // object equals value
Setting component properties 49
If you want to create a single element array, include the <mx:Array> and </mx:Array> tags
around the array element, as the following example shows:
<mynamespace:MyComponent>
<mynamespace:nameOfObjectProperty>
<mx:Array>
<mx:Number>94062</mx:Number>
</mx:Array>
</mynamespace:nameOfObjectProperty>
</mynamespace:MyComponent>
Populating Arrays of objects
When a component has a property that takes an Array of objects as its value, you can
represent the property in MXML using child tags, as the following example shows:
<mynamespace:MyComponent>
<mynamespace:nameOfProperty>
<mx:Array>
<mynamespace:objectType prop1="val1" prop2="val2"/>
<mynamespace:objectType prop1="val1" prop2="val2"/>
<mynamespace:objectType prop1="val1" prop2="val2"/>
</mx:Array>
</mynamespace:nameOfProperty>
</mynamespace:MyComponent>
The component in the following example contains an Array of ListItem objects. Each
ListItem object has properties named label and data.
<mynamespace:MyComponent>
<mynamespace:dataProvider>
<mx:Array>
<mynamespace:ListItem label="One" data="1"/>
<mynamespace:ListItem label="Two" data="2"/>
</mx:Array>
</mynamespace:dataProvider>
</mynamespace:MyComponent>
The following example shows how you specify an anonymous object as the value of the
dataProvider property:
<mynamespace:MyComponent>
<mynamespace:dataProvider>
<mx:Array>
<mx:Object label="One" data="1"/>
<mx:Object label="Two" data="2"/>
</mx:Array>
</mynamespace:dataProvider>
</mynamespace:MyComponent>
50 MXML Syntax
As described in the section “Setting Arrays of scalar values” on page 47, the <mx:Array> tag
and the </mx:Array> tag around the Array elements are optional and may be omitted, as the
following example shows:
<mynamespace:MyComponent>
<mynamespace:dataProvider>
<mx:Object label="One" data="1"/>
<mx:Object label="Two" data="2"/>
</mynamespace:dataProvider>
</mynamespace:MyComponent>
Setting properties that contain XML data
If a component contains a property that takes XML data, the value of the property is an XML
fragment to which you can apply a namespace. In the following example, the value property
of the MyComponent object is XML data:
<mynamespace:MyComponent>
<mynamespace:value xmlns:a="http://www.example.com/myschema">
<mx:XML>
<a:purchaseorder>
<a:billingaddress>
...
</a:billingaddress>
...
</a:purchaseorder>
</mx:XML>
</mynamespace:value>
</mynamespace:MyComponent>
Setting style and effect properties in MXML
A style or effect property of an MXML tag differs from other properties because it
corresponds to an ActionScript style or effect, rather than to a property of an ActionScript
class. You set these properties in ActionScript using the setStyle(stylename, value)
method rather than object.property=value notation.
You define style or effect properties in ActionScript classes using the [Style] or [Effect]
metadata tags, rather than defining them as ActionScript variables or setter/getter methods.
For more information, see Chapter 5, “Using Metadata Tags in Custom Components,” in
Creating and Extending Flex 2 Components.
For example, you can set the fontFamily style property in MXML, as the following code
shows:
<mx:TextArea id="myText" text="hello world" fontFamily="Tahoma"/>
Setting component properties 51
This MXML code is equivalent to the following ActionScript code:
myText.setStyle("fontFamily", "Tahoma");
Setting event properties in MXML
An event property of an MXML tag lets you specify the event listener function for an event.
This property correspond to setting the event listener in ActionScript using the
addEventListener() method.
You define event properties in ActionScript classes using the [Event] metadata tags, rather
than defining them as ActionScript variables or setter/getter methods. For more information,
see Chapter 5, “Using Metadata Tags in Custom Components,” in Creating and Extending
Flex 2 Components.
For example, you can set the creationComplete event property in MXML, as the following
code shows:
<mx:TextArea id="myText" creationComplete="creationCompleteHandler()"/>
This MXML code is equivalent to the following ActionScript code:
myText.addEventListener("creationComplete", creationCompleteHandler);
Specifying a URL value
Some MXML tags, such as the <mx:Script> tag, have a property that takes a URL of an
external file as a value. For example, you can use the source property in an <mx:Script> tag
to reference an external ActionScript file instead of typing ActionScript directly in the body of
the <mx:Script> tag.
You specify a script in the source property of an <mx:Script> tag. You do not specify
NO T E
ActionScript classes in the source property. For information on using ActionScript
classes, see “Creating ActionScript components” on page 75 in the Flex 2 Developer’s
Guide.
MXML supports the following types of URLs:
■ Absolute; for example:
<mx:Style source="http://www.somesite.com/mystyles.css">
■ A path used at run time that is relative to the context root of the Java web application in
which a Flex application is running; for example:
<mx:HTTPService url="@ContextRoot()/directory/myfile.xml"/>
52 MXML Syntax
■ A path used at compile-time that is relative to the context root of the Java web application
in which a Flex application is running; for example:
<mx:Script source="/myscript.as"/>
■ Relative to the current file location; for example:
<mx:Script source="../myscript.as"/>
Specifying a RegExp value
For a property of type RegExp, you can specify its value in MXML using the following
format:
"/pattern/flags"
pattern Specifies the regular expression within the two slashes. Both slashes are required.
flags (Optional) specifies any flags for the regular expression.
For example, the regExpression property of an MXML component is of type RegExp.
Therefore, you can set its value, as the following example shows:
<mynamespace:MyComponent regExpression="/\Wcat/gi"/>
Or set it using child tags, as the following example shows:
<mynamespace:MyComponent>
<mynamespace:regExpression>/\Wcat/gi</mynamespace:regExpression>
</mynamespace:MyComponent>
The flags portion of the regular expression is optional, so you can also specify it as the
following example shows:
<mynamespace:MyComponent regExpression="/\Wcat/"/>
Using compiler tags
Compiler tags are tags that do not directly correspond to ActionScript objects or properties.
The names of the following compiler tags have just the first letter capitalized:
■ <mx:Binding>
■ <mx:Component>
■ <mx:Metadata>
■ <mx:Model>
■ <mx:Script>
■ <mx:Style>
■ <mx:XML>
■ <mx:XMLList>
Setting component properties 53
The following compiler tags are in all lowercase letters:
■ <mx:operation>
■ <mx:request>
■ <mx:method>
■ <mx:arguments>
MXML tag rules
MXML has the following syntax requirements:
■ The id property is not required on any tag.
■ The id property is not allowed on the root tag.
■ Boolean properties take only true and false values.
■ The <mx:Binding> tag requires both source and destination properties.
■ The <mx:Binding> tag cannot contain an id property.
■ The <mx:WebService> tag requires a wsdl value or serviceName value, and does not
allow both.
■ The <mx:RemoteObject> tag requires a source value or a named value, and does not
allow both.
■ The <mx:HTTPService> tag requires a url value or a serviceName value, and does not
allow both.
■ The <mx:operation> tag requires a name value, and does not allow duplicate name
entries.
■ The <mx:operation> tag cannot contain an id property.
■ The <mx:method> tag requires a name value and does not allow duplicate name entries.
■ The <mx:method> tag cannot contain an id property.
54 MXML Syntax
4
CHAPTER 4
Using ActionScript
Flex developers can use ActionScript to extend the functionality of their Adobe Flex
applications. ActionScript provides flow control and object manipulation features that are not
available in MXML. This topic explains how to use ActionScript in an MXML application.
For a complete introduction to ActionScript and a reference for using the language, see
Programming ActionScript 3.0 and ActionScript 3.0 Language Reference.
Contents
Using ActionScript in Flex applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Working with Flex components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Comparing, including, and importing ActionScript code. . . . . . . . . . . . . . . . . . . . . . . 68
Techniques for separating ActionScript from MXML . . . . . . . . . . . . . . . . . . . . . . . . . 72
Creating ActionScript components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Performing object introspection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Using ActionScript in Flex applications
Flex developers can use ActionScript to implement custom behavior within their Flex
applications. You first use MXML tags to declare things like the containers, controls, effects,
formatters, validators, and web services that your application requires, and to lay out its user
interface. Each of these components provides the standard behavior you’d expect. For
example, a button automatically highlights when you roll over it, without requiring you to
write any ActionScript. But a declarative language like MXML is not appropriate for coding
what you want to happen when the user clicks a button. For that, you need to use a
procedural language like ActionScript, which offers executable methods, various types of
storage variables, and flow control such as conditionals and loops. In a general sense, MXML
implements the static aspects of your application, and ActionScript implements its dynamic
aspects.
55
ActionScript is an object-oriented procedural programming language, based on the
ECMAScript (ECMA-262) edition 4 draft language specification. You can use a variety of
methods to mix ActionScript and MXML, including the following:
■ Use ActionScript to define event listeners inside MXML event attributes.
■ Add script blocks using the <mx:Script> tag.
■ Include external ActionScript files.
■ Import ActionScript classes.
■ Create ActionScript components.
ActionScript compilation
Although a simple Flex application can be written in a single MXML or ActionScript (AS)
file, most applications will be broken into multiple files. For example, it is common to move
the <mx:Script> and <mx:Style> blocks for an <mx:Application> into separate AS and
CSS files which the application then includes. It is also common for an application to import
custom MXML and ActionScript components. These must be defined in other files, and
MXML components may put their own <mx:Script> blocks into yet more AS files that they
include. Components may also be imported from precompiled SWC files rather than source
code. Finally, SWF files containing executable code can also be embedded in an application.
The end result of all these input files is a single SWF file.
You can use ActionScript code fragments in a number of places within your MXML files. The
Flex compiler transforms the main MXML file and other files it includes into a single
ActionScript class. So, you cannot define classes or use statements outside of functions in
MXML files and included ActionScript files.
You can reference imported ActionScript classes from your MXML application files, and
those classes are added to the final SWF file. When the transformation to an ActionScript file
is complete, Flex links all the ActionScript components and includes those classes in the final
SWF file.
About generated ActionScript
When you write an MXML file and compile it, the Flex compiler creates a new class and
generates ActionScript that the class uses. The following list describes the ways that MXML
tags and ActionScript are used by the resulting class. You do not necessarily have to
understand the information in this section to use Flex, but it can be useful for understanding
what is happening out of view of the Flex developer.
56 Using ActionScript
An MXML application (a file starting with the <mx:Application> tag) defines a subclass of
the Application class. Similarly, an MXML component (a file starting with some other
component’s tag, such as <mx:Button>) defines a subclass of that component.
The name of the subclass is the name of the file. The base class is the class of the top-level tag.
An MXML application actually defines the following:
class MyApp extends Application
If MyButton.mxml starts with <mx:Button>, you are actually defining the following:
class MyButton extends Button
The variable and function declarations in an <mx:Script> block define properties and
methods of the subclass.
Setting an id property on a component instance within a class results in a public variable
being autogenerated in the subclass that contains a reference to that component instance. For
example, if the <mx:Button id="myButton"/> tag is nested deeply inside several containers,
you can still refer to it as myButton.
Event attributes become the bodies of autogenerated event listener methods in the subclass.
For example:
<mx:Button id="myButton" click="foo = 1; doSomething()">
becomes
private function __myButton_click(event:MouseEvent):void {
foo = 1;
doSomething()
}
The event attributes become method bodies, so they can access the other properties and
methods of the subclass.
All the ActionScript anywhere in an MXML file, whether in its <mx:Script> block or inside
tags, executes with the this keyword referring to an instance of the subclass.
The public properties and methods of the class are accessible by ActionScript code in other
components, as long as that code “dots down” (for example,
myCheckoutAccordion.myAddressForm.firstNameTextInput.text) or reaches up using
parentDocument, parentApplication, or Application.application to specify which
component the property or method exists on.
Using ActionScript in Flex applications 57
Using ActionScript in MXML event handlers
One way to use ActionScript code in a Flex application is to include it within the MXML tag’s
event handler, as the following example shows:
<?xml version="1.0"?>
<!-- usingas/HelloWorldAS.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Panel title="My Application" >
<mx:TextArea id="textarea1"/>
<mx:Button label="Submit" click="textarea1.text='Hello World';"/>
</mx:Panel>
</mx:Application>
In this example, you include ActionScript code for the body of the click event handler of the
Button control. The MXML compiler takes the attribute click="..." and generates the
following event handler method:
public function __myButton_click(event:MouseEvent):void {
textarea1.text='Hello World';
}
When the user clicks the button, this code sets the value of the TextArea control’s text
property to the String “Hello World.” In most cases, you do not need to look at the
generated code, but it is useful to understand what happens when you write an inline event
handler.
To see the generated code, set the value of the keep-generated-actionscript compiler
option to true. The compiler then stores the *.as helper file in the /generated directory, which
is a subdirectory of the location of the SWF file.
For more information about events, see Chapter 5, “Using Events,” on page 83. For more
information on using the command-line compilers, see Chapter 9, “Using the Flex
Compilers,” in Building and Deploying Flex 2 Applications.
Using ActionScript blocks in MXML files
You use the <mx:Script> tag to insert an ActionScript block in an MXML file. ActionScript
blocks can contain ActionScript functions and variable declarations used in MXML
applications. Code inside <mx:Script> tags can also declare constants (with the const
statement) and namespaces (with namespace), include ActionScript files (with include),
import declarations (with import), and use namespaces (with use namespace).
The <mx:Script> tag must be a child of the <mx:Application> or other top-level
component tag.
58 Using ActionScript
Statements and expressions are allowed only if they are wrapped in a function. In addition,
you cannot define new classes or interfaces in <mx:Script> blocks. Instead, you must place
new classes or interfaces in separate AS files and import them.
All ActionScript in the block is added to the enclosing file’s class when Flex compiles the
application. The following example declares a variable and sets the value of that variable inside
a function:
<?xml version="1.0"?>
<!-- usingas/StatementSyntax.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="doSomething()">
<mx:Script><![CDATA[
public var s:Boolean;
public function doSomething():void {
// The following statements must be inside a function.
s = label1.visible;
label1.text = String(s);
}
]]></mx:Script>
<mx:Label id="label1"/>
</mx:Application>
Most statements must be inside functions in an <mx:Script> block. However, the following
statements can be outside functions:
■ import
■ var
■ include
■ const
■ namespace
■ use namespace
When using an <mx:Script> block, you should wrap the contents in a CDATA construct.
This prevents the compiler from interpreting the contents of the script block as XML, and
allows the ActionScript to be properly generated. Adobe recommends that you write all your
<mx:Script> open and close tags as the following example shows:
<mx:Script>
<![CDATA[
...
]]>
</mx:Script>
Using ActionScript in Flex applications 59
Flex does not parse text in a CDATA construct so that you can use XML-parsed characters
such as angle brackets (< and >) and ampersand (&). For example, the following script that
includes a less than (<) comparison must be in a CDATA construct:
<?xml version="1.0"?>
<!-- usingas/UsingCDATA.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="doSomething()">
<mx:Script><![CDATA[
public var m:Number;
public var n:Number;
public function doSomething():void {
n = 42;
m = 40;
label1.text = String(n > m);
}
]]></mx:Script>
<mx:Label id="label1"/>
</mx:Application>
Accessing ActionScript documentation
The ActionScript 3.0 programming language can be used from within several development
environments, including Flash Professional and Adobe Flex Builder.
The Flex documentation includes Programming ActionScript 3.0, which describes the
ActionScript language. The ActionScript API reference is included as part of the Adobe Flex 2
Language Reference.
Working with Flex components
The primary use of ActionScript in your Flex applications is probably going to be for working
with the visual controls and containers in your application. This section describes techniques
for doing this, including how to reference a Flex control in ActionScript and how to
manipulate properties during the control’s and container’s instantiation.
Referring to Flex components
To work with a component in ActionScript, you usually define an id property for that
component in the MXML tag. For example, the following code sets the id property of the
Button control to the String "myButton":
<mx:Button id="myButton" label="Click Me"/>
60 Using ActionScript
This property is optional if you do not want to access the component with ActionScript.
This code causes the MXML compiler to autogenerate a public variable named myButton that
contains a reference to that Button instance. This autogenerated variable lets you access the
component instance in ActionScript. You can explicitly refer to the Button control’s instance
with its id instance reference in any ActionScript class or script block. By referring to a
component’s instance, you can modify its properties and call its methods.
For example, the following ActionScript block changes the value of the Button control’s
label property when the user clicks the button:
<?xml version="1.0"?>
<!-- usingas/ButtonExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
private function setLabel():void {
myButton.label = "Clicked";
}
]]></mx:Script>
<mx:Button id="myButton" label="Click Me" click="setLabel();"/>
</mx:Application>
The IDs for all tags in an MXML component, no matter how deeply nested they are, generate
public variables of the component being defined. As a result, all id properties must be unique
within a document. This also means that if you specified an ID for a component instance, you
can access that component from anywhere in the application: from functions, external class
files, imported ActionScript files, or inline scripts.
You can refer to a Flex component if it does not have an id property by using methods of the
component’s container, such as the getChildAt() and getChildByName() methods.
You can refer to the current enclosing document or current object using the this keyword.
You can also get a reference to a component when you have a String that matches the name.
To access an object on the application, you use the this keyword, followed by square
brackets, with the String inside the square brackets. The result is a reference to the objects
whose name matches the String.
Working with Flex components 61
The following example changes style properties on each Button control using a compound
String to get a reference to the object:
<?xml version="1.0"?>
<!-- usingas/FlexComponents.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
public function changeLabel(s:String):void {
s = "myButton" + s;
this[s].setStyle("fontStyle","italic");
this[s].setStyle("fontSize","18");
}
]]></mx:Script>
<mx:Button id="myButton1" click="changeLabel('2')" label="Change Other
Button's Styles"/>
<mx:Button id="myButton2" click="changeLabel('1')" label="Change Other
Button's Styles"/>
</mx:Application>
This technique is especially useful if you use a Repeater control or when you create objects in
ActionScript and do not necessarily know the names of the objects you want to refer to prior
to run time. However, when you instantiate an object in ActionScript, to add that object to
the properties array, you must declare the variable as public and declare it in the class’s scope,
not inside a function.
62 Using ActionScript
The following example uses ActionScript to declare two Label controls in the application
scope. During initialization, the labels are instantiated and their text properties are set. The
example then gets a reference to the Label controls by appending the passed in variable to the
String when the user clicks the Button controls.
<?xml version="1.0"?>
<!-- usingas/ASLabels.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="initLabels()">
<mx:Script><![CDATA[
import mx.controls.Label;
public var label1:Label;
public var label2:Label;
// Objects must be declared in the application scope. Adds the names to
// the application's properties array.
public function initLabels():void {
label1 = new Label();
label1.text = "Change Me";
label2 = new Label();
label2.text = "Change Me";
addChild(label1);
addChild(label2);
}
public function changeLabel(s:String):void {
// Create a String that matches the name of the Label control.
s = "label" + s;
// Get a reference to the label control using the
// application's properties array.
this[s].text = "Changed";
}
]]></mx:Script>
<mx:Button id="b1" click="changeLabel('2')" label="Change Other Label"/>
<mx:Button id="b2" click="changeLabel('1')" label="Change Other Label"/>
</mx:Application>
Calling component methods
You can invoke the public methods of a component instance in your Flex application by using
the following dot-notation syntax:
componentInstance.method([parameters]);
Working with Flex components 63
The following example invokes the adjustThumb() method when the user clicks the button,
which invokes the public setThumbValueAt() method of the HSlider control:
<?xml version="1.0"?>
<!-- usingas/ComponentMethods.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
public function adjustThumb(s:HSlider):void {
s.setThumbValueAt(0,4);
}
]]></mx:Script>
<mx:HSlider id="slider1"/>
<mx:Button id="myButton" label="Set Thumb"
click="adjustThumb(slider1);"/>
</mx:Application>
To invoke a method from a child document (such as a custom MXML component), you can
use the parentApplication, parentDocument, or Application.application properties.
For more information, see Chapter 14, “Using the Application Container,” on page 529.
Creating visual Flex components in ActionScript
You can use ActionScript to programmatically create visual Flex components using the new
operator, in the same way that you create instances of any ActionScript class. The created
component has default values for its properties, but it does not yet have a parent or any
children (including any kind of internal DisplayObjects), and it is not yet on the display list
in Flash Player, so you can’t see it. After creating the component, you should use standard
assignment statements to set any properties whose default values aren’t appropriate.
Finally, you must add the new component to a container, by using that container’s
addChild() or addChildAt() method, so that it becomes part of the visual hierarchy of a
Flex application. The first time that it is added to a container, a component’s children are
created. Children are created late in the component’s life cycle so that you can set properties
that can affect children as they are created.
When creating visual controls, you must import the appropriate package. In most cases, this is
the mx.controls package, although you should check Adobe Flex 2 Language Reference.
64 Using ActionScript
The following example creates a Button control inside the HBox:
<?xml version="1.0"?>
<!-- usingas/ASVisualComponent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
import mx.controls.Button;
public var button2:Button;
public function createObject():void {
button2 = new Button();
button2.label = "Click Me";
hb1.addChild(button2);
}
]]></mx:Script>
<mx:HBox id="hb1">
<mx:Button label="Create Object" click="createObject()"/>
</mx:HBox>
</mx:Application>
Flex creates the new child as the last child in the container. If you do not want the new child
to be the last in the container, use the addChildAt() method to change the order. You can the
setChildIndex() method after the call to the addChild() method, but this is less efficient.
You should declare an instance variable for each dynamically created component and store a
reference to the newly created component in it, just as the MXML compiler does when you
set an id property for a component instance tag. You can then access your dynamically
created components in the same way as those declaratively created in MXML.
To programmatically remove a control, you can use the removeChild() or removeChildAt()
methods. You can also use the removeAllChildren() method to remove all child controls
from a container. Calling these methods does not actually delete the objects. If you do not
have any other references to the child, Flash Player includes it in garbage collection at some
future point. But if you stored a reference to that child on some object, the child is not
removed from memory.
In some cases, you declaratively define a component with an MXML tag. You can set the
creationPolicy property of the component’s container to none to defer the creation of the
controls inside that container. Then, to create a component that has been declared with a tag
but not instantiated, you use the createComponentFromDescriptor() and
createComponentsFromDescriptors() methods. These methods let you create a
component programmatically rather than declaratively. For information on using the
creationPolicy property, see Chapter 6, “Improving Startup Performance,” in Building and
Deploying Flex 2 Applications.
Working with Flex components 65
The only component you can pass to the addChild() method is a UIComponent. In other
words, if you create a new object that is not a subclass of mx.core.UIComponent, you must
wrap it in a UIComponent before you can attach it to a container. The following example
creates a new Sprite object, which is not a subclass of UIComponent, and adds it as a child of
the UIComponent before adding it to the Panel container:
<?xml version="1.0"?>
<!-- usingas/AddingChildrenAsUIComponents.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
import flash.display.Sprite;
import mx.core.UIComponent;
private function addChildToPanel():void {
var circle:Sprite = new Sprite();
circle.graphics.beginFill(0xFFCC00);
circle.graphics.drawCircle(0, 0, 20);
var c:UIComponent = new UIComponent();
c.addChild(circle);
panel1.addChild(c);
}
]]></mx:Script>
<mx:Panel id="panel1" height="100" width="100"/>
<mx:Button id="myButton" label="Click Me" click="addChildToPanel();"/>
</mx:Application>
About scope
Scoping in ActionScript is largely a description of what the this keyword refers to at a
particular point. In your application’s core MXML file, you can access the Application object
by using the this keyword. In a file defining an MXML component, this is a reference to
the current instance of that component.
In an ActionScript class file, the this keyword refers to the instance of that class. In the
following example, the this keyword refers to an instance of myClass. Because this is
implicit, you do not have to include it, but it is shown here to illustrate its meaning.
class myClass {
var _x:Number = 3;
function get x():Number {
return this._x;
}
66 Using ActionScript
function set x(y:Number):void {
if (y > 0) {
this._x = y;
} else {
this._x = 0;
}
}
}
However, in custom ActionScript and MXML components or external ActionScript class files,
Flex executes in the context of those objects and classes, and the this keyword refers to the
current scope and not the Application object scope.
Flex includes an Application.application property that you can use to access the root
application. You can also use the parentDocument property to access the next level up in the
document chain of a Flex application, or the parentApplication property to access the next
level up in the application chain when one Application object uses a SWFLoader component
to load another Application object.
If you write ActionScript in a component’s event listener, the scope is not the component but
rather the application. For example, the following code changes the label of the Button
control to “Clicked” once the Button control is pressed:
<?xml version="1.0"?>
<!-- usingas/ButtonScope.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Button id="myButton" label="Click Me"
click="myButton.label='Clicked'"/>
</mx:Application>
Contrast the previous example with the following code:
<?xml version="1.0"?>
<!-- usingas/AppScope.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<!-- The following does nothing because the app level scope does
not have a label to set -->
<mx:Button id="myButton" label="Click Me" click="label='Clicked'"/>
</mx:Application>
This code does not work because when an event listener executes, the this keyword does not
refer to the Button instance; it is the Application or other top-level component instance. The
second example attempts to set the label property of the Application object, not the label
property of the Button.
Working with Flex components 67
Variables declared within a function are locally scoped to that function. These variables can
share the same name as variables in outer scopes, and they do not affect the outer-scoped
variable. If a variable is just used temporarily by a single method, make it a local variable of
that method, not an instance variable. Use instance variables only for storing the state of an
instance, because each instance variable will take up memory for the entire lifetime of the
instance. You can refer to the outer-scoped variable with the this. prefix.
Comparing, including, and importing
ActionScript code
To make your MXML code more readable, you can reference ActionScript files in your
<mx:Script> tags, rather than insert large blocks of script. You can either include or import
ActionScript files.
There is a distinct difference between including and importing code in ActionScript.
Including copies lines of code from one file into another, as if they had been pasted at the
position of the include statement. Importing adds a reference to a class file or package so that
you can access objects and properties defined by external classes. Files that you import must
be found in the source path. Files that you include must be located relative to the file using
the import statement, or you must use an absolute path.
You use the include statement or the <mx:Script source="filename"> tag to add
ActionScript code to your Flex applications.
You use import statements in an <mx:Script> block to define the locations of ActionScript
classes and packages that your Flex applications might use.
The following sections contain more detail on including and importing ActionScript code.
Including ActionScript files
To include ActionScript code, you reference an external ActionScript file in your
<mx:Script> tags. At compile time, the compiler copies the entire contents of the file into
your MXML application, as if you had actually typed it. As with ActionScript in an
<mx:Script> block, ActionScript in included files can only consist of variable declarations if
outside functions. Included files can also declare constants and namespaces, include other
ActionScript files, import declarations, and use namespaces. You cannot define classes in
included files.
68 Using ActionScript
Variables and functions defined in an included ActionScript file are available to any
component in the MXML file. An included ActionScript file is not the same as an imported
ActionScript class. Flex provides access to the included file’s variables and functions, but does
not add a new class, because the MXML file itself is a class.
Included ActionScript files do not need to be in the same directory as the MXML file.
However, you should organize your ActionScript files in a logical directory structure.
If you are using Adobe Flex Data Services, Flex detects changes in ActionScript files using
timestamps. If the file has changed since the last request, Flex regenerates the application
before responding to the client. If you change the ActionScript in one of the imported
ActionScript files, the next time the application is requested, the changes appear.
There are two ways to include an external ActionScript file in your Flex application:
■ The source attribute of the <mx:Script> tag. This is the preferred method for including
external ActionScript class files.
■ The include statement inside <mx:Script> blocks.
The following sections describe these two methods of including an external ActionScript file.
Using the source attribute to include ActionScript files
You use the source attribute of the <mx:Script> tag to include external ActionScript files in
your Flex applications. This provides a way to make your MXML files less cluttered and
promotes code reuse across different applications.
Do not give the script file the same name as the application file. This causes a compiler error.
The following example shows the contents of the IncludedFile.as file:
// usingas/includes/IncludedFile.as
public function computeSum(a:Number, b:Number):Number {
return a + b;
}
The following example imports the contents of the IncludedFile.as file. This file is located in
the includes subdirectory.
<?xml version="1.0"?>
<!-- usingas/SourceInclude.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script source="includes/IncludedFile.as"/>
<mx:TextInput id="ta1st" text="3"/>
<mx:TextInput id="ta2nd" text="3"/>
<mx:TextArea id="taMain"/>
<mx:Button id="b1" label="Compute Sum"
click="taMain.text=String(computeSum(Number(ta1st.text),
Number(ta2nd.text)));"/>
</mx:Application>
Comparing, including, and importing ActionScript code 69
The source attribute of the <mx:Script> tag supports both relative and absolute paths. For
more information, see “Referring to external files that have been included” on page 71.
You cannot use the source attribute of an <mx:Script> tag and wrap ActionScript code
inside that same <mx:Script> tag. To include a file and write ActionScript in the MXML file,
use two <mx:Script> tags.
Using the include directive
The include directive is an ActionScript statement that copies the contents of the specified
file into your MXML file. The include directive uses the following syntax:
include "file_name";
The following example includes the myfunctions.as file:
<?xml version="1.0"?>
<!-- usingas/AppScope.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
include "includes/myfunctions.as";
]]></mx:Script>
<mx:Button id="myButton" label="Click Me"
click="doSomething();doSomethingElse()"/>
</mx:Application>
You can specify only a single file for each include directive, but you can use any number of
include directives. You can nest include directives; files with include directives can include
files that have include directives.
The include directive supports only relative paths. For more information, see “Referring to
external files that have been included” on page 71.
You can use the include only where multiple statements are allowed. For example, the
following is not allowed:
if (expr)
include "foo.as"; // First statement is guarded by IF, but rest are not.
...
The following is allowed:
if (expr) {
include "foo.as"; // All statements inside { } are guarded by IF.
}
70 Using ActionScript
The use of curly braces ({ }) allows multiple statements because you can add multiple
statements inside the braces.
Adobe recommends that you not use the include directive if you use a large number of
included ActionScript files. You should try to break the code into separate class files where
appropriate and store them in logical package structures.
Referring to external files that have been included
The source attribute of the <mx:Script> tag and the include directive refer to files in
different ways.
The following are the valid paths to external files that are referenced in an <mx:Script> tag’s
source attribute:
■ Flex Data Services only: Site-relative URLs, such as /scripts/myscript.as. A URL that
begins with a slash is resolved relative to the context root of the application. The default
application root is /flex_app_root.
■ Relative URLs, such as ../myscript.as. A relative URL that does not start with a slash is
resolved relative to the file that uses it. If the tag <mx:Script source="../
IncludedFile.as"> is included in “mysite/myfiles/myapp.mxml,” the system searches
for “mysite/IncludedFile.as”.
For an ActionScript include directive, you can only reference relative URLs.
Flex searches the source path for imported classes and packages. Flex does not search the
source path for files that are included using the include directive or the source attribute of
the <mx:Script> tag.
Importing classes and packages
If you create many utility classes or include multiple ActionScript files to access commonly
used functions, you might want to store them in a set of classes in their own package. You can
import ActionScript classes and packages using the import statement. By doing this, you do
not have to explicitly enter the fully qualified class names when accessing classes within
ActionScript.
Comparing, including, and importing ActionScript code 71
The following example imports the MyClass class in the MyPackage.Util package:
<?xml version="1.0"?>
<!-- usingas/AccessingPackagedClasses.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
import MyPackage.Util.MyClass;
private var mc:MyClass = new MyClass;
]]></mx:Script>
<mx:Button id="myButton" label="Click Me"
click="myButton.label=mc.returnAString()"/>
</mx:Application>
In your ActionScript code, instead of referring to the class with its fully qualified package
name (MyPackage.Util.MyClass), you refer to it as MyClass.
You can also use the wildcard character (*) to import the entire package. For example, the
following statement imports the entire MyPackage.Util package:
import MyPackage.Util.*;
Flex searches the source path for imported files and packages, and includes only those that are
used in the final SWF file.
It is not sufficient to simply specify the fully qualified class name. You should use fully
qualified class names only when necessary to distinguish two classes with the same class name
that reside in different packages.
If you import a class but do not use it in your application, the class is not included in the
resulting SWF file’s bytecode. As a result, importing an entire package with a wildcard does
not create an unnecessarily large SWF file.
Techniques for separating ActionScript
from MXML
This section follows a single sample application to show how it uses several different methods
of separating ActionScript from the MXML. The Temperature application takes input from a
single input field and uses a function to convert the input from Fahrenheit to Celsius. It then
displays the resulting temperature in a Label control.
72 Using ActionScript
The following image shows the sample Temperature application:
In this simple application that calls a single function, there are several ways to separate
MXML and ActionScript:
■ “One MXML document (Event handling logic in event attribute)” on page 73
■ “One MXML document (Event handling logic in <mx:Script> block)” on page 74
■ “One MXML document and one ActionScript file (Event handling logic in separate script
file)” on page 75
The following sections describe these methods.
One MXML document (Event handling logic in event
attribute)
The following code shows the ActionScript event handling logic inside the MXML tag’s
click event:
<?xml version="1.0"?>
<!-- usingas/ASOneFile.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Panel title="My Application" paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10">
<mx:HBox>
<mx:Label text="Temperature in Farenheit:"/>
<mx:TextInput id="farenheit" width="120"/>
<mx:Button label="Convert"
click="celsius.text=String((Number(farenheit.text)-32)/1.8);"/>
<mx:Label text="Temperature in Celsius:"/>
<mx:Label id="celsius" width="120" fontSize="24"/>
</mx:HBox>
</mx:Panel>
</mx:Application>
Techniques for separating ActionScript from MXML 73
One MXML document (Event handling logic in
<mx:Script> block)
In this example, the logic for the function is inside an <mx:Script> block in the MXML
document, and is called from the MXML tag’s click event, as the following code shows:
<?xml version="1.0"?>
<!-- usingas/ASScriptBlock.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
public function calculate():void {
var n:Number = Number(farenheit.text);
celsius.text=String((n-32)/1.8);
}
]]></mx:Script>
<mx:Panel title="My Application" paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10">
<mx:HBox>
<mx:Label text="Temperature in Farenheit:"/>
<mx:TextInput id="farenheit" width="120"/>
<mx:Button label="Convert" click="calculate();" />
<mx:Label text="Temperature in Celsius:"/>
<mx:Label id="celsius" width="120" fontSize="24"/>
</mx:HBox>
</mx:Panel>
</mx:Application>
74 Using ActionScript
One MXML document and one ActionScript file
(Event handling logic in separate script file)
Here the function call is in an MXML event attribute, and the function is defined in a
separate ActionScript file, as the following code shows:
<?xml version="1.0"?>
<!-- usingas/ASSourceFile.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<!-- Specify the ActionScript file that contains the function. -->
<mx:Script source="includes/Sample3Script.as"/>
<mx:Panel title="My Application" paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10">
<mx:HBox>
<mx:Label text="Temperature in Farenheit:"/>
<mx:TextInput id="farenheit" width="120"/>
<mx:Button label="Convert" click="calculate();"/>
<mx:Label text="Temperature in Celsius:"/>
<mx:Label id="celsius" width="120" fontSize="24"/>
</mx:HBox>
</mx:Panel>
</mx:Application>
The Sample3Script.as ActionScript file contains the following code:
// usingas/includes/Sample3Script.as
public function calculate():void {
celsius.text=String((Number(farenheit.text)-32)/1.8);
}
Creating ActionScript components
You can create reusable components that use ActionScript, and reference these components in
your Flex applications as MXML tags. Components created in ActionScript can contain
graphical elements, define custom business logic, or extend existing Flex components. They
can inherit from any components available in Flex.
Defining your own components in ActionScript has several benefits. Components let you
divide your applications into individual modules that you can develop and maintain
separately. By implementing commonly used logic within custom components, you can build
a suite of reusable components that you can share among multiple Flex applications.
Also, you can base your custom components on the set of Flex components by extending from
the Flex class hierarchy. You can create custom versions of Flex visual controls, as well as
custom versions on nonvisual components, such as data validators, formatters, and effects.
Creating ActionScript components 75
For example, you can define a custom button, derived from the Button control, in the
myControls package, as the following example shows:
package myControls {
import mx.controls.Button;
public class MyButton extends Button {
public function MyButton() {
...
}
...
}
}
In this example, you write your MyButton control to the MyButton.as file, and you store the
file in the myControls subdirectory of the root directory of your Flex application. The fully
qualified class name of your component reflects its location. In this example, the component’s
fully qualified class name is myControls.MyButton.
You can reference your custom Button control from a Flex application file, such as
MyApp.mxml, as the following example shows:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:cmp="myControls.*">
<cmp:MyButton label="Jack"/>
</mx:Application>
In this example, you define the cmp namespace that defines the location of your custom
component in the application’s directory structure. You then reference the component as an
MXML tag using the namespace prefix.
Typically, you put custom ActionScript components in directories that are in the source path.
These include your application’s root directory, the flex_app_root/WEB-INF/flex/user_classes
directory (Flex Data Services only), or any directory that you specify in the <source-path>
tag in the flex-config.xml file.
You can also create custom components using MXML. For more information, see Creating
and Extending Flex 2 Components.
Types of custom components
You can create the following types of components in ActionScript:
User-interface components User-interface components contain both processing logic and
visual elements. These components usually extend the Flex component hierarchy. You can
extend from the UIComponent classes, or any of the Flex components, such as Button,
ComboBox, or DataGrid. Your custom ActionScript component inherits all of the public
methods and public and protected properties of its base class.
76 Using ActionScript
Nonvisual components Nonvisual components define no visual elements. A nonvisual
component is an ActionScript class that does not extend the UIComponent class. They can
provide greater efficiency at run time.
Performing object introspection
Object introspection is a technique for determining the elements of a class at run time, such as
its properties and methods. There are two ways to do introspection in ActionScript:
■ Using for..in loops
■ Using the introspection API
This section describes how to use both these methods.
You might find object introspection a useful technique when debugging your application. For
example, you might write a method that takes a generic object of type Object as an argument.
You can use introspection to output all of the properties and methods of the Object to
determine exactly what your application passed to it.
Using for..in loops
A for..in loop enumerates only dynamically added properties. Declared variables and
methods of classes are not enumerated in for..in loops. This means that most classes in the
ActionScript API will not display any properties in a for..in loop. The generic type Object
is still a dynamic object and will display properties in a for..in loop.
Performing object introspection 77
The following example creates a generic Object, adds properties to that object, and then
iterates over that object when you click the button to inspect its properties:
<?xml version="1.0"?>
<!-- usingas/IntrospectionForIn.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="initApp()">
<mx:Script><![CDATA[
private var obj:Object = new Object();
private function initApp():void {
// Create the object.
obj.a = "Schotten Totten";
obj.b = "Taj Majal";
obj.c = "Durche die Wuste";
}
public function dumpObj():void {
for (var p:String in obj) {
ta1.text += p + ":" + obj[p] + "\n";
}
}
]]></mx:Script>
<mx:TextArea id="ta1" width="400" height="500"/>
<mx:Button label="Dump Object" click="dumpObj()"/>
</mx:Application>
78 Using ActionScript
You can also use the mx.utils.ObjectUtil.toString() method to print all the
dynamically added properties of an object; for example:
<?xml version="1.0"?>
<!-- usingas/IntrospectionForIn.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="initApp()">
<mx:Script><![CDATA[
import mx.utils.ObjectUtil;
private var obj:Object = new Object();
private function initApp():void {
// Create the object.
obj.a = "Schotten Totten";
obj.b = "Taj Majal";
obj.c = "Durche die Wuste";
}
public function dumpObj():void {
ta1.text = ObjectUtil.toString(obj);
}
]]></mx:Script>
<mx:TextArea id="ta1" width="400" height="500"/>
<mx:Button label="Dump Object" click="dumpObj()"/>
</mx:Application>
The mx.utils.ObjectUtil class has other useful methods such as compare(), copy(), and
isSimple(). For more information, see Adobe Flex 2 Language Reference.
Using the introspection API
If you want to list all the public properties and methods of a nondynamic (or sealed) class or
class instance, use the describeType() method and parse the results using the E4X API. The
describeType() method is in the flash.utils package. The method’s only parameter is the
target object that you want to introspect. You can pass it any ActionScript value, including all
available ActionScript types such as object instances, primitive types such as uint, and class
objects. The return value of the describeType() method is an E4X XML object that
contains an XML description of the object’s type.
The describeType() method returns only public members. The method does not return
private members of the caller’s superclass or any other class where the caller is not an instance.
If you call describeType(this), the method returns information only about nonstatic
members of the class. If you call describeType(getDefinitionByName("MyClass")), the
method returns information only about the target’s static members.
Performing object introspection 79
The following example introspects the Button control and prints the details to TextArea
controls:
<?xml version="1.0"?>
<!-- usingas/IntrospectionAPI.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="getDetails()">
<mx:Script><![CDATA[
import flash.utils.*;
public function getDetails():void {
// Get the Button control's E4X XML object description.
var classInfo:XML = describeType(button1);
// Dump the entire E4X XML object into ta2.
ta2.text = classInfo.toString();
// List the class name.
ta1.text = "Class " +
[email protected]() + "\n";
// List the object's variables, their values, and their types.
for each (var v:XML in classInfo..variable) {
ta1.text += "Variable " + v.@name + "=" + button1[v.@name] +
" (" + v.@type + ")\n";
}
// List accessors as properties.
for each (var a:XML in classInfo..accessor) {
// Do not get the property value if it is write only.
if (a.@access == 'writeonly') {
ta1.text += "Property " + a.@name + " (" + a.@type +")\n";
}
else {
ta1.text += "Property " + a.@name + "=" +
button1[a.@name] + " (" + a.@type +")\n";
}
}
// List the object's methods.
for each (var m:XML in classInfo..method) {
ta1.text += "Method " + m.@name + "():" + m.@returnType +
"\n";
}
}
]]></mx:Script>
<mx:Button label="Submit" id="button1"/>
<mx:TextArea id="ta1" width="400" height="200"/>
<mx:TextArea id="ta2" width="400" height="200"/>
</mx:Application>
80 Using ActionScript
The output displays accessors, variables, and methods of the Button control, and appears
similar to the following:
Class mx.controls::Button
...
Variable id=button1 (String)
Variable __width=66 (Number)
Variable layoutWidth=66 (Number)
Variable __height=22 (Number)
Variable layoutHeight=22 (Number)
...
Property label=Submit (String)
Property enabled=true (Boolean)
Property numChildren=2 (uint)
Property enabled=true (Boolean)
Property visible=true (Boolean)
Property toolTip=null (String)
...
Method dispatchEvent():Boolean
Method hasEventListener():Boolean
Method layoutContents():void
Method getInheritingStyle():Object
Method getNonInheritingStyle():Object
Another useful method is the ObjectUtil’s getClassInfo() method. This method returns an
Object with the name and properties of the target object. The following example uses the
getClassInfo() and toString() methods to show the properties of the Button control:
<?xml version="1.0"?>
<!-- usingas/IntrospectionObjectUtil.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
import mx.controls.Alert;
import mx.utils.ObjectUtil;
private function showProps(b:Button):void {
var o:Object = ObjectUtil.getClassInfo(b);
ta1.text = ObjectUtil.toString(o);
}
]]></mx:Script>
<mx:Button id="b1" label="Show Properties" click="showProps(b1)"/>
<mx:TextArea id="ta1" width="300" height="500"/>
</mx:Application>
For more information about using E4X, see Programming ActionScript 3.0.
Performing object introspection 81
82 Using ActionScript
5
CHAPTER 5
Using Events
One of the most important parts of your Adobe Flex application is handling events. This
topic describes the event flow and how to handle events by using controls and ActionScript in
your Flex applications.
Contents
About events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Using events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Manually dispatching events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Event propagation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .112
Event priorities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119
Using event subclasses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .121
About keyboard events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
About events
This section introduces you to the event model in Flex 2. In addition, this section describes
the Event object and its subclasses, and describes the event dispatching model. For a quick
start in using events in Flex, you can skip this section and see sample code in “Using events”
on page 87.
Events let a developer know when something happens within a Flex application. They can be
generated by user devices, such as the mouse and keyboard, or other external input, such as
the return of a web service call. Events are also triggered when changes happen in the
appearance or life cycle of a component, such as the creation or destruction of a component or
when the component is resized.
83
Any user interaction with your application can generate events. Events can also occur without
any direct user interaction, such as when data finishes loading from a server or when an
attached camera becomes active. You can “handle” these events in your code by adding an
event handler. Event handlers are the functions or methods that you write to respond to
specific events. They are also sometimes referred to as event listeners.
The Flex event model is based on the Document Object Model (DOM) Level 3 Events
Model. Although Flex does not adhere specifically to the Document Object Model standard,
the implementations are very similar.
Components generate and dispatch events and consume (listen to) other events. An object that
requires information about another object’s events registers a listener with that object. When
an event occurs, the object dispatches the event to all registered listeners by calling a function
that was requested during registration. To receive multiple events from the same object, you
must register your listener for each event.
Components have built-in events that you can handle in ActionScript blocks in your MXML
applications. You can also take advantage of the Flex event system’s dispatcher-listener model
to define your own event listeners outside of your applications, and define which methods of
your custom listeners will listen to certain events. You can register listeners with the target
object so that when the target object dispatches an event, the listeners get called.
All visual objects, including Flex controls and containers, are subclasses of the DisplayObject
class. They are in a tree of visible objects that make up your application. The root of the tree is
the Stage. Below that is the SystemManager object, and then the Application object. Child
containers and components are leaf nodes of the tree. That tree is known as the display list. An
object on the display list is analogous to a node in the DOM hierarchical structure. The terms
display list object and node are used interchangeably in this topic.
For information about each component’s events, see the component’s description in Chapter
9, “Using Controls,” on page 259 or the control’s entry in Adobe Flex 2 Language Reference.
For a detailed description of a component’s startup life cycle, including major events in that
life cycle, see Chapter 10, “Creating Advanced Visual Components in ActionScript,” in
Creating and Extending Flex 2 Components.
84 Using Events
About the Event flow
You can instruct any container or control to listen for events dispatched by another container
or control. When Adobe Flash Player dispatches an Event object, that Event object makes a
round-trip journey from the root of the display list to the target node, checking each node for
registered listeners. The target node is the node in the display list where the event occurred.
For example, if a user clicks a Button control named Child1, Flash Player dispatches an Event
object with Child1 defined as the target node.
The event flow is conceptually divided into three parts. The following sections introduce you
to these parts. For more information about the event flow, see “Event propagation”
on page 112.
About the capturing phase
The first part of the event flow is called the capturing phase, which comprises all of the nodes
from the root node to the parent of the target node. During this phase, Flash Player examines
each node, starting with the root, to see if it has a listener registered to handle the event. If it
does, Flash Player sets the appropriate values of the Event object and then calls that listener.
Flash Player stops after it reaches the target node’s parent and calls any listeners registered on
the parent. For more information about the capturing phase, see “Capturing phase”
on page 114.
About the targeting phase
The second part of the event flow is called the targeting phase, which consists solely of the
target node. Flash Player sets the appropriate values on the Event object, checks the target
node for registered event listeners, and then calls those listeners. For more information about
the targeting phase, see “Targeting phase” on page 115.
About the bubbling phase
The third part of the event flow is called the bubbling phase, which comprises all of the nodes
from the target node’s parent to the root node. Starting with the target node’s parent, Flash
Player sets the appropriate values on the Event object and then calls event listeners on each of
these nodes. Flash Player stops after calling any listeners on the root node. For more
information about the bubbling phase, see “Bubbling phase” on page 115.
About events 85
About the Event class
The flash.events.Event class is an ActionScript class with properties that contain information
about the event that occurred. An Event object is an implicitly created object, similar to the
way the request and response objects in a JavaServer Page (JSP) are implicitly created by the
application server.
Flex creates an Event object each time an event is dispatched. You can use the Event object
inside an event listener to access details about the event that was dispatched, or about the
component that dispatched the event. Passing an Event object to, and using it in, an event
listener is optional. However, if you want to access the Event object’s properties inside your
event listeners, you must pass the Event object to the listener.
Flex creates only one Event object when an event is dispatched. During the bubbling and
capturing phases, Flex changes the values on the Event object as it moves up or down the
display list, rather than creating a new Event object for each node.
About event subclasses
There are many classes that extend the flash.events.Event class. These classes are defined
mostly in the following two packages:
■ mx.events.*
■ flash.events.*
The mx.events package defines event classes that are specific to Flex controls, including the
DataGridEvent, DragEvent, and ColorPickerEvent. The flash.events package describes events
that are not unique to Flex but are instead defined by Flash Player. These event classes include
MouseEvent, DataEvent, and TextEvent. All of these events are commonly used in Flex
applications.
In addition to these packages, some packages also define their own event objects; for example,
mx.messaging.events.ChannelEvent and mx.logging.LogEvent.
Child classes of the Event class have additional properties and methods that may be unique to
them. In some cases you will want to use a more specific event type rather than the generic
Event object so that you can access these unique properties or methods. For example, the
LogEvent class has a getLevelString() method that the Event class does not.
For information on using Event subclasses, see “Using event subclasses” on page 121.
86 Using Events
About the EventDispatcher class
Every object in the display list can trace its class inheritance back to the DisplayObject class.
The DisplayObject class, in turn, inherits from the EventDispatcher class. The
EventDispatcher class is a base class that provides important event model functionality for
every object on the display list. Because the DisplayObject class inherits from the
EventDispatcher class, any object on the display list has access to the methods of the
EventDispatcher class.
This is significant because every item on the display list can participate fully in the event
model. Every object on the display list can use its addEventListener() method—inherited
from the EventDispatcher class—to listen for a particular event, but only if the listening
object is part of the event flow for that event.
Although the name EventDispatcher seems to imply that this class’s main purpose is to send
(or dispatch) Event objects, the methods of this class are used much more frequently to
register event listeners, check for event listeners, and remove event listeners.
The EventDispatcher class implements the IEventDispatcher interface. This allows developers
who create custom classes that cannot inherit from EventDispatcher or one of its subclasses to
implement the IEventDispatcher interface to gain access to its methods.
The addEventListener() method is the most commonly used method of this class. You use
it to register your event listeners. For information on using the addEventListener()
method, see “Using the addEventListener() method” on page 95.
Advanced programmers use the dispatchEvent() method to manually dispatch an event or
to send a custom Event object into the event flow. For more information, see “Manually
dispatching events” on page 109.
Several other methods of the EventDispatcher class provide useful information about the
existence of event listeners. The hasEventListener() method returns true if an event
listener is found for that specific event type on a particular display list object. The
willTrigger() method checks for event listeners on a particular display list object, but it
also checks for listeners on all of that display list object’s ancestors for all phases of the event
flow. The method returns true if it finds one.
Using events
Using events in Flex is a two-step process. First, you write a function or class method, known
as an event listener or event handler, that responds to events. The function often accesses the
properties of the Event object or some other settings of the application state. The signature of
this function usually includes an argument that specifies the event type being passed in.
Using events 87
The following example shows a simple event listener function that reports when a control
triggers the event that it is listening for:
<?xml version="1.0"?>
<!-- events/SimpleEventHandler.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="initApp()">
<mx:Script><![CDATA[
import mx.controls.Alert;
private function initApp():void {
b1.addEventListener(MouseEvent.CLICK, myEventHandler);
}
private function myEventHandler(event:Event):void {
Alert.show("An event occurred");
}
]]></mx:Script>
<mx:Button id="b1" label="Click Me" click="myEventHandler(event)"/>
</mx:Application>
As you can see in this example, you also register that function or class method with a display
list object by using the addEventListener() method.
Most Flex controls simplify listener registration by letting you specify the listener inside the
MXML tag. For example, instead of using the addEventListener() method to specify a
listener function for the Button control’s click event, you specify it in the click attribute of
the <mx:Button> tag:
<?xml version="1.0"?>
<!-- events/SimplerEventHandler.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
import mx.controls.Alert;
private function myEventHandler(event:Event):void {
Alert.show("An event occurred");
}
]]></mx:Script>
<mx:Button id="b1" label="Click Me" click="myEventHandler(event)"/>
</mx:Application>
88 Using Events
This is equivalent to the addEventListener() method in the previous code example.
However, it is best practice to use the addEventListener() method. This method gives you
greater control over the event by letting you configure the priority and capturing settings, and
use event constants. In addition, if you use addEventListener() to add an event handler,
you can use removeEventListener() to remove the handler when you no longer need it. If
you add an event handler inline, you cannot call removeEventListener() on that handler.
Each time a control generates an event, Flex creates an Event object that contains information
about that event, including the type of event and a reference to the dispatching control. To
use the Event object, you specify it as a parameter in the event handler function, as the
following example shows:
<?xml version="1.0"?>
<!-- events/EventTypeHandler.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
import mx.controls.Alert;
private function myEventHandler(e:Event):void {
Alert.show("An event of type " + e.type + " occurred.");
}
]]></mx:Script>
<mx:Button id="b1" label="Click Me" click="myEventHandler(event)"/>
</mx:Application>
If you want to access the Event object in an event handler that was triggered by an inline
event, you must add the event keyword inside the MXML tag so that Flex explicitly passes it
to the handler, as in the following:
<mx:Button id="b1" label="Click Me" click="myEventHandler(event)"/>
Using events 89
You are not required to use the Event object in a handler function. The following example
creates two event handler functions and registers them with the events of a ComboBox
control. The first event handler, openEvt(), takes no arguments. The second event handler,
changeEvt(), takes the Event object as an argument and uses this object to access the value
and selectedIndex of the ComboBox control that triggered the event.
<?xml version="1.0"?>
<!-- events/MultipleEventHandlers.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
private function openEvt():void {
forChange.text="";
}
private function changeEvt(e:Event):void {
forChange.text=e.currentTarget.value + " " +
e.currentTarget.selectedIndex;
}
]]></mx:Script>
<mx:ComboBox open="openEvt()" change="changeEvt(event)">
<mx:dataProvider>
<mx:Array>
<mx:String>AK</mx:String>
<mx:String>AL</mx:String>
<mx:String>AR</mx:String>
</mx:Array>
</mx:dataProvider>
</mx:ComboBox>
<mx:TextArea id="forChange" width="150"/>
</mx:Application>
This example shows accessing the target property of the Event object. For more
information, see “Accessing the target property” on page 91.
Specifying the Event object
You specify the object in a listener function’s signature as type Event, as the following example
shows:
function myEventListener(e:Event):void { ... }
However, if you want to access properties that are specific to the type of event that was
dispatched, you must instead specify a more specific event type, such as ToolTipEvent or
KeyboardEvent, as the following example shows:
import mx.events.ToolTip
function myEventListener(e:ToolTipEvent):void { ... }
In some cases, you must import the event’s class in your ActionScript block.
90 Using Events
Most objects have specific events that are associated with them, and most of them can
dispatch more than one type of event.
If you declare an event of type Event, you can cast it to a more specific type to access its event-
specific properties. For more information, see “Using event subclasses” on page 121.
Accessing the target property
Event objects include a reference to the instance of the dispatching component (or target). So,
you can access all the properties and methods of that instance in an event listener. The
following example accesses the id of the button control that triggered the event:
<?xml version="1.0"?>
<!-- events/AccessingCurrentTarget.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
import mx.controls.Alert;
private function myEventHandler(e:Event):void {
Alert.show("The button " + e.currentTarget.id + " was clicked");
}
]]></mx:Script>
<mx:Button id="b1" label="Click Me" click="myEventHandler(event)"/>
</mx:Application>
Calling methods and accessing properties on the current target can be confusing. The type of
the currentTarget property is DisplayObject. Because ActionScript is strongly typed, you
can call event.currentTarget.methodName() only if methodName is a method defined on
DisplayObject. The same applies for properties. You can access
event.currentTarget.property only if the property is defined on DisplayObject. If you
try to call another method on the currentTarget (for example, the setStyle() method),
Flex returns an error. The setStyle() method is defined on UIComponent, a subclass of
DisplayObject. Therefore, you must cast currentTarget to UIComponent before calling the
setStyle() method, as the following example shows:
<?xml version="1.0"?>
<!-- events/InvokingOnCurrentTarget.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
import mx.core.UIComponent;
private function myEventHandler(e:Event):void {
UIComponent(e.currentTarget).setStyle("color", "red");
}
]]></mx:Script>
<mx:Button id="b1" label="Click Me" click="myEventHandler(event)"/>
</mx:Application>
Using events 91
You can also access methods and properties of the target, which contains a reference to the
current node in the display list. For more information, see “About the target and
currentTarget properties” on page 113.
Registering event handlers
There are several strategies that you can employ when you register event handlers with your
Flex controls:
■ Define an event handler inline. This binds a call to the handler function to the control
that triggers the event.
<?xml version="1.0"?>
<!-- events/SimplerEventHandler.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
import mx.controls.Alert;
private function myEventHandler(event:Event):void {
Alert.show("An event occurred");
}
]]></mx:Script>
<mx:Button id="b1" label="Click Me" click="myEventHandler(event)"/>
</mx:Application>
In this example, whenever the user clicks the Button control, Flex calls the
myClickHandler() function.
For more information on defining event handlers inline, see “Defining event listeners
inline” on page 93.
92 Using Events
■ Use the addEventListener() method, as follows:
<?xml version="1.0"?>
<!-- events/SimpleEventHandler.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="initApp()">
<mx:Script><![CDATA[
import mx.controls.Alert;
private function initApp():void {
b1.addEventListener(MouseEvent.CLICK, myEventHandler);
}
private function myEventHandler(event:Event):void {
Alert.show("An event occurred");
}
]]></mx:Script>
<mx:Button id="b1" label="Click Me" click="myEventHandler(event)"/>
</mx:Application>
As with the previous example, whenever the user clicks the Button control, Flex calls the
myClickHandler() handler function. But registering your event handlers using this
method provides more flexibility. You can register multiple components with this event
handler, add multiple handlers to a single component, or remove the handler. For more
information, see “Using the addEventListener() method” on page 95.
■ Create an event handler class and register components to use the class for event handling.
This approach to event handling promotes code reuse and lets you centralize event
handling outside your MXML files. For more information on creating custom event
handler classes, see “Creating event handler classes” on page 99.
The following sections describe these methods of handling events.
Defining event listeners inline
The simplest method of defining event handlers in Flex applications is to point to a handler
function in the component’s MXML tag. To do this, you add any of the component’s events
as a tag attribute followed by an ActionScript statement or function call.
You add an event handler inline using the following syntax:
<mx:tag_name event_name="handler_function"/>
For example, to listen for a Button control’s click event, you add a statement in the
<mx:Button> tag’s click attribute. If you add a function, you define that function in an
ActionScript block. The following example defines the submitForm() function as the handler
for the Button control’s click event:
Using events 93
<mx:Script><![CDATA[
function submitForm():void {
// Do something.
}
]]></mx:Script>
<mx:Button label="Submit" click="submitForm();" />
Event handlers can include any valid ActionScript code, including code that calls global
functions or sets a component property to the return value. The following example calls the
trace() global function:
<mx:Button label="Get Ver" click="trace('The button was clicked');"/>
There is one special parameter that you can pass in an inline event handler definition: the
event parameter. If you add the event keyword as a parameter, Flex passes the Event object.
Inside the handler function, you can then access all the properties of the Event object.
The following example passes the Event object to the submitForm() handler function and
specifies it as type MouseEvent:
<?xml version="1.0"?>
<!-- events/MouseEventHandler.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
private function myEventHandler(event:MouseEvent):void {
// Do something with the MouseEvent object;
}
]]></mx:Script>
<mx:Button id="b1" label="Click Me" click="myEventHandler(event)"/>
</mx:Application>
It is best practice to include the event keyword when you define all inline event listeners and
to specify the most stringent Event object type in the resulting listener function (for example,
specify MouseEvent instead of Event).
You can use the Event object to access a reference to the target object (the object that
dispatched the event), the type of event (for example, click), or other relevant properties,
such as the row number and value in a list-based control. You can also use the Event object to
access methods and properties of the target component, or the component that dispatched the
event.
94 Using Events
Although you will most often pass the entire Event object to an event listener, you can just
pass individual properties, as the following example shows:
<?xml version="1.0"?>
<!-- events/PropertyHandler.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
private function myEventHandler(s:String):void {
trace(s);
}
]]></mx:Script>
<mx:Button id="b1" label="Click Me"
click="myEventHandler(event.currentTarget.id)"/>
</mx:Application>
Registering an event listener inline provides less flexibility than using the
addEventListener() method to register event listeners. The drawbacks are that you cannot
set the useCapture or priority properties on the Event object and that you cannot remove
the listener once you add it.
Using the addEventListener() method
The addEventListener() method lets you register event listener functions with the specified
control or object. The following example adds the myClickListener() function to the b1
instance of a Button control. When the user clicks b1, Flex calls the myClickListener()
method:
b1.addEventListener(MouseEvent.CLICK, myClickListener);
The addEventListener() method has the following signature:
componentInstance.addEventListener(event_type:String,
event_listener:Function, use_capture:Boolean, priority:int,
weakRef:Boolean)
The event_type argument is the kind of event that this component dispatches. This can be
either the event type String (for example, click or mouseOut), or the event type static
constant (such as MouseEvent.CLICK or MouseEvent.MOUSE_OUT). This argument is
required.
The constants provide an easy way to refer to specific event types. You should use these
constants instead of the strings that they represent. If you misspell a constant name in your
code, the compiler catches the mistake. If you instead use strings and make a typographical
error, it can be harder to debug and could lead to unexpected behavior.
Using events 95
You should use the constants wherever possible. For example, when you are testing to see
whether an Event object is of a certain type, use the following code:
if (myEventObject.type == MouseEvent.CLICK) {/* your code here */}
rather than:
if (myEventObject.type == "click") {/* your code here */}
The event_listener argument is the function that handles the event. This argument is
required.
The use_capture parameter of the addEventListener() method lets you control the phase
in the event flow in which your listener will be active. It sets the value of the useCapture
property of the Event object. If useCapture is set to true, your listener is active during the
capturing phase of the event flow. If useCapture is set to false, your listener is active during
the targeting and bubbling phases of the event flow but not during the capturing phase. The
default value is determined by the type of event, but is false in most cases.
To listen for an event during all phases of the event flow, you must call addEventListener()
twice, once with the use_capture parameter set to true, and again with use_capture set to
false. This argument is optional. For more information, see “Capturing phase” on page 114.
The priority parameter sets the priority for that event listener. The higher the number, the
sooner that event handler executes relative to other event listeners for the same event. Event
listeners with the same priority are executed in the order that they were added. This parameter
sets the priority property of the Event object. The default value is 0, but you can set it to
negative or positive integer values. If several event listeners were added without priorities, the
earlier a listener is added, the sooner it is executed. For more information on setting priorities,
see “Event priorities” on page 119.
The weakRef parameter provides you with some control over memory resources for listeners.
A strong reference (when weakRef is false) prevents the listener from being garbage
collected. A weak reference (when weakRef is true) does not. The default value is false.
When you add a listener function and that function is invoked, Flex implicitly creates an
Event object for you and passes it to the listener function. You must declare the Event object
in the signature of your listener function.
If you add an event listener by using the addEventListener() method, you are required to
declare an event object as a parameter of the listener_function, as the following example
shows:
b1.addEventListener(MouseEvent.CLICK, performAction);
In the listener function, you declare the Event object as a parameter, as follows:
public function performAction(e:MouseEvent):void {
...
}
96 Using Events
The following example defines a new handler function myClickListener(). It then registers
the click event of the Button control with that handler. When the user clicks the button,
Flex calls the myClickHandler() function.
<?xml version="1.0"?>
<!-- events/AddEventListenerExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="createListener()">
<mx:Script><![CDATA[
import mx.controls.Alert;
private function createListener():void {
b1.addEventListener(MouseEvent.CLICK, myClickHandler, false, 0);
}
private function myClickHandler(e:MouseEvent):void {
Alert.show("The button was clicked");
}
]]></mx:Script>
<mx:Button label="Click Me" id="b1"/>
</mx:Application>
Using addEventListener() inside an MXML tag
You can add event listeners with the addEventListener() method inline with the
component definition. The following Button control definition adds the call to the
addEventListener() method inline with the Button control’s initialize property:
<?xml version="1.0"?>
<!-- events/CallingAddEventListenerInline.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
import mx.controls.Alert;
private function myClickHandler(event:Event):void {
Alert.show("This is a log message");
}
]]></mx:Script>
<mx:Button id='b1'
label="Click Me"
initialize='b1.addEventListener(MouseEvent.CLICK, myClickHandler,
false, 1);'
/>
</mx:Application>
Using events 97
This is the equivalent of defining the event handler inline. However, defining a handler by
using the addEventListener() method rather than setting click="handler_function"
lets you set the value of the useCapture and priority properties of the Event object.
Furthermore, you cannot remove a handler added inline, but when you use the
addEventListener() method to add a handler, you can call the removeEventListener()
method to remove that handler.
Removing event handlers
It is a good idea to remove any handlers that will no longer be used. This removes references
to objects so that they can be cleared from memory. You can use the
removeEventListener() method to remove an event handler that you no longer need. All
components that can call addEventListener() can also call the removeEventListener()
method. The syntax for the removeEventListener() method is as follows:
componentInstance.removeEventListener(event_type:String,
listener_function:Function, use_capture:Boolean)
For example, consider the following code:
myButton.removeEventListener(MouseEvent.CLICK, myClickHandler);
The event_type and listener_function parameters are required. These are the same as the
required parameters for the addEventListener() method.
The use_capture parameter is also identical to the parameter used in the
addEventListener() method. Recall that you can listen for events during all event phases by
calling addEventListener() twice; once with use_capture set to true, and again with it set
to false. To remove both event listeners, you must call removeEventListener() twice; once
with use_capture set to true, and again with it set to false.
You can only remove event listeners that you added with the addEventListener() method
in an ActionScript block. You cannot remove an event listener that was defined in the MXML
tag, even if it was registered using a call to the addEventListener() method that was made
inside a tag attribute.
98 Using Events
The following sample application shows what type of handler can be removed and what type
cannot:
<?xml version="1.0"?>
<!-- events/RemoveEventListenerExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="createHandler(event)">
<mx:Script><![CDATA[
import mx.controls.Alert;
private function createHandler(e:Event):void {
b1.addEventListener(MouseEvent.CLICK, myClickHandler);
}
private function removeMyHandlers(e:Event):void {
// Remove listener for b1's click event.
b1.removeEventListener(MouseEvent.CLICK,myClickHandler);
// Does NOT remove the listener for b2's click event.
b2.removeEventListener(MouseEvent.CLICK,myClickHandler);
}
private function myClickHandler(e:Event):void {
Alert.show("This is a log message");
}
]]></mx:Script>
<mx:Button id="b1" label="Click Me"/>
<mx:Button label="Click Me Too" id="b2" click="myClickHandler(event)"/>
<mx:Button label="Axe Listeners" id="b3" click="removeMyHandlers(event)"/
>
</mx:Application>
Creating event handler classes
You can create an external class file and use the methods of this class as event handlers.
Objects themselves cannot be event handlers, but methods of an object can be. By defining
one class that handles all your event handlers, you can use the same event handling logic
across applications, which can make your MXML applications more readable and
maintainable.
Using events 99
To create a class that handles events, you usually import the flash.events.Event class. You also
usually write an empty constructor. The following ActionScript class file calls the trace()
function whenever it handles an event with the handleAllEvents() method:
// events/MyEventHandler.as
package { // Empty package
import flash.events.Event;
public class MyEventHandler {
public function MyEventHandler() {
// Empty constructor
}
public function handleAllEvents(event:Event):void {
trace("some event happened");
}
}
}
In your MXML file, you declare a new instance of MyEventHandler and use the
addEventListener() method to register its handleAllEvents() method as a handler to the
Button control’s click event, as the following example shows:
<?xml version="1.0"?>
<!-- events/CustomHandler.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="createHandler()">
<mx:Script><![CDATA[
private var myListener:MyEventHandler = new MyEventHandler();
private function createHandler():void {
b1.addEventListener(MouseEvent.CLICK, myListener.handleAllEvents);
}
]]></mx:Script>
<mx:Button label="Submit" id="b1"/>
</mx:Application>
100 Using Events
The best approach is to define the event handler’s method as static. By doing this, you are no
longer required to instantiate the class inside your MXML application. The following
createHandler() function registers the handleAllEvents() method as an event handler
without instantiating the MyStaticEventHandler class:
<?xml version="1.0"?>
<!-- events/CustomHandlerStatic.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="createHandler()">
<mx:Script><![CDATA[
private function createHandler():void {
b1.addEventListener(MouseEvent.CLICK,
MyStaticEventHandler.handleAllEvents);
}
]]></mx:Script>
<mx:Button label="Submit" id="b1"/>
</mx:Application>
In the class file, you just add the static keyword to the method signature:
// events/MyStaticEventHandler.as
package { // Empty package
import flash.events.Event;
public class MyStaticEventHandler {
public function MyStaticEventHandler() {
// Empty constructor
}
public static function handleAllEvents(event:Event):void {
trace("some event happened");
}
}
}
Store your event listener class in a directory in your source path. You can also store your
ActionScript class in the same directory as your MXML file, although Adobe does not
recommend this.
Using events 101
Defining multiple listeners for a single event
You can define multiple event handler functions for a single event in two ways. When
defining events inside MXML tags, you separate each new handler function with a semicolon.
The following example adds the submitForm() and debugMessage() functions as handlers
of the click event:
<?xml version="1.0"?>
<!-- events/MultipleEventHandlersInline.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
private function submitForm(e:Event):void {
// Handle event here.
}
private function debugMessage(e:Event):void {
// Handle event here.
}
]]></mx:Script>
<mx:Button id="b1"
label="Do Both Actions"
click='submitForm(event); debugMessage(event);'
/>
</mx:Application>
102 Using Events
For events added with the addEventListener() method, you can add any number of
handlers with additional calls to the addEventListener() method. Each call adds a handler
function that you want to register to the specified object. The following example registers the
submitForm() and debugMessage() handler functions with b1’s click event:
<?xml version="1.0"?>
<!-- events/MultipleEventHandlersAS.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="createHandlers(event)">
<mx:Script><![CDATA[
public function createHandlers(e:Event):void {
b1.addEventListener(MouseEvent.CLICK, submitForm);
b1.addEventListener(MouseEvent.CLICK, debugMessage);
}
private function submitForm(e:Event):void {
// Handle event here.
}
private function debugMessage(e:Event):void {
// Handle event here.
}
]]></mx:Script>
<mx:Button id="b1" label="Click Me"/>
</mx:Application>
Using events 103
You can mix the methods of adding event handlers to any component; alternatively, you can
add handlers inline and with the addEventListener() method. The following example adds
a click event handler inline for the Button control which calls the performAction()
method. It then conditionally adds a second click handler to call the logAction() method,
depending on the state of the CheckBox control.
<?xml version="1.0"?>
<!-- events/ConditionalHandlers.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="initApp(event)">
<mx:Script><![CDATA[
import mx.controls.Alert;
private function initApp(e:Event):void {
cb1.addEventListener(MouseEvent.CLICK, handleCheckBoxChange);
b1.addEventListener(MouseEvent.CLICK, logAction);
}
private function handleCheckBoxChange(e:Event):void {
if (cb1.selected) {
b1.addEventListener(MouseEvent.CLICK, logAction);
ta1.text += "added log listener" + "\n";
} else {
b1.removeEventListener(MouseEvent.CLICK, logAction);
ta1.text += "removed log listener" + "\n";
}
}
private function performAction(e:Event):void {
Alert.show("You performed the action");
}
private function logAction(e:Event):void {
ta1.text += "Action performed: " + e.type + "\n";
}
]]></mx:Script>
<mx:Button label="Perform Action" id="b1" click="performAction(event)"/>
<mx:CheckBox id="cb1" label="Log?" selected="true"/>
<mx:TextArea id="ta1" height="200" width="300"/>
</mx:Application>
You can set the order in which event listeners are called by using the priority parameter of
the addEventListener() method. You cannot set a priority for a listener function if you
added the event listener using MXML inline. For more information on setting priorities, see
“Event priorities” on page 119.
104 Using Events
Registering a single listener with multiple components
You can register the same listener function with any number of events of the same
component, or events of different components. The following example registers a single
listener function, submitForm(), with two different buttons:
<?xml version="1.0"?>
<!-- events/OneHandlerTwoComponentsInline.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
private function submitForm(e:Event):void {
// Handle event here.
trace(e.currentTarget.id);
}
]]></mx:Script>
<mx:Button id="b1"
label="Click Me"
click="submitForm(event)"
/>
<mx:Button id="b2"
label="Click Me"
click="submitForm(event)"
/>
</mx:Application>
Using events 105
When you use the addEventListener() method to register a single listener to handle the
events of multiple components, you must use a separate call to the addEventListener()
method for each instance, as the following example shows:
<?xml version="1.0"?>
<!-- events/OneHandlerTwoComponentsAS.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="createHandlers(event)">
<mx:Script><![CDATA[
public function createHandlers(e:Event):void {
b1.addEventListener(MouseEvent.CLICK, submitForm);
b2.addEventListener(MouseEvent.CLICK, submitForm);
}
private function submitForm(e:Event):void {
// Handle event here.
trace(e.currentTarget.id);
}
]]></mx:Script>
<mx:Button id="b1" label="Click Me"/>
<mx:Button id="b2" label="Click Me Too"/>
</mx:Application>
When doing this, you should add logic to the event listener that processes the type of event.
The event target (or object that dispatched the event) is added to the Event object for you. No
matter what triggered the event, you can conditionalize the event processing based on the
target or type properties of the Event object. Flex adds these two properties to all Event
objects.
106 Using Events
The following example registers a single listener function (myEventHandler()) to the click
event of a Button control and the click event of a CheckBox control. To detect what type of
object called the event listener, the listener checks the className property of the target in the
Event object in a case statement:
<?xml version="1.0"?>
<!-- events/ConditionalTargetHandler.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="initApp()">
<mx:Script><![CDATA[
public function initApp():void {
button1.addEventListener(MouseEvent.CLICK, myEventHandler);
cb1.addEventListener(MouseEvent.MOUSE_DOWN, myEventHandler);
}
public function myEventHandler(event:Event):void {
switch (event.currentTarget.className) {
case "Button":
// Process Button click.
break;
case "CheckBox":
// Process CheckBox click.
break;
}
}
]]></mx:Script>
<mx:Button label="Submit" id="button1"/>
<mx:CheckBox label="All Words" id="cb1"/>
<mx:TextArea id="ta1" text="Please enter a search term" width="200"/>
</mx:Application>
Passing additional parameters to listener functions
You can pass additional parameters to listener functions depending on how you add the
listeners. If you add a listener with the addEventListener() method, you cannot pass any
additional parameters to the listener function, and that listener function can only declare a
single argument, the Event object (or one of its subclasses).
For example, the following code throws an error because the clickListener() method
expects two arguments:
<mx:Script>
public function addListeners():void {
b1.addEventListener(MouseEvent.CLICK,clickListener);
}
public function clickListener(e:MouseEvent, a:String):void { ... }
</mx:Script>
<mx:Button id="b1"/>
Using events 107
Because the second parameter of addEventListener() is a function, you cannot specify
parameters of that function in the addEventListener() call. So, to pass additional
parameters to the listener function, you must define them in the listener function and then
call the final method with those parameters. If you define an event listener inline (inside the
MXML tag), you can add any number of parameters as long as the listener function’s
signature agrees with that number of parameters. The following example passes a string and
the Event object to the runMove() method:
<?xml version="1.0"?>
<!-- events/MultipleHandlerParametersInline.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
public function runMove(dir:String, e:Event):void {
if (dir == "up") {
moveableButton.y = moveableButton.y - 5;
} else if (dir == "down") {
moveableButton.y = moveableButton.y + 5;
} else if (dir == "left") {
moveableButton.x = moveableButton.x - 5;
} else if (dir == "right") {
moveableButton.x = moveableButton.x + 5;
}
}
]]></mx:Script>
<mx:Canvas height="100%" width="100%">
<mx:Button id="moveableButton"
label="{moveableButton.x.toString()},{moveableButton.y.toString()}"
x="200"
y="200"
width="80"
/>
</mx:Canvas>
<mx:VBox horizontalAlign="center">
<mx:Button id="b1"
label="Up"
click='runMove("up",event);'
width="50"
/>
<mx:HBox horizontalAlign="center">
<mx:Button id="b2"
label="Left"
click='runMove("left",event);'
width="50"
/>
<mx:Button id="b3"
label="Right"
click='runMove("right",event);'
108 Using Events
width="50"
/>
</mx:HBox>
<mx:Button id="b4"
label="Down"
click='runMove("down",event);'
width="50"
/>
</mx:VBox>
</mx:Application>
Manually dispatching events
You can manually dispatch events using a component instance’s dispatchEvent() method.
All components that extend UIComponent have this method. The method is inherited from
the EventDispatcher class which UIComponent extends.
The syntax for the dispatchEvent() method is as follows:
objectInstance.dispatchEvent(event:Event):Boolean
When dispatching an event, you must create a new Event object. The syntax for the Event
object constructor is as follows:
Event(event_type:String, bubbles:Boolean, cancelable:Boolean)
The event_type parameter is the type property of the Event object. The bubbles and
cancelable parameters are optional and both default to false. For information on bubbling
and capturing, see “Event propagation” on page 112.
Manually dispatching events 109
You can use the dispatchEvent() method to dispatch any event you want, not just a custom
event. You can dispatch a Button control’s click event, even though the user did not click a
Button control, as in the following example:
<?xml version="1.0"?>
<!-- events/DispatchEventExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="createListener(event)">
<mx:Script><![CDATA[
import mx.controls.Alert;
private function createListener(e:Event):void {
b1.addEventListener(MouseEvent.MOUSE_OVER, myEventHandler);
b1.addEventListener(MouseEvent.CLICK, myClickHandler);
}
private function myEventHandler(e:Event):void {
var result:Boolean = b1.dispatchEvent(new
MouseEvent(MouseEvent.CLICK, true, false));
}
private function myClickHandler(e:Event):void {
Alert.show("Triggered by the " + e.type + " event");
}
]]></mx:Script>
<mx:Button id="b1" label="Click Me"/>
</mx:Application>
You can also manually dispatch an event in an MXML tag. In the following example, moving
the mouse pointer over the button triggers the button’s click event:
<?xml version="1.0"?>
<!-- events/DispatchEventExampleInline.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="createListener(event)">
<mx:Script><![CDATA[
import mx.controls.Alert;
private function createListener(e:Event):void {
b1.addEventListener(MouseEvent.CLICK, myClickHandler);
}
private function myClickHandler(e:Event):void {
Alert.show("Triggered by the " + e.type + " event");
}
]]></mx:Script>
<mx:Button id="b1" label="Click Me" mouseOver="b1.dispatchEvent(new
MouseEvent(MouseEvent.CLICK, true, false))"/>
</mx:Application>
Your Flex application is not required to handle the newly dispatched event. If you trigger an
event that has no listeners, Flex ignores the event.
110 Using Events
You can set properties of the Event object in ActionScript, but you cannot add new properties
because the object is not dynamic. The following example intercepts a click event. It then
creates a new MouseEvent object and dispatches it. In addition, it sets the value of the
shiftKey property of the MouseEvent object to true, to simulate a Shift-click on the
keyboard.
<?xml version="1.0"?>
<!-- events/DispatchCustomizedEvent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="addListeners()">
<mx:Script><![CDATA[
private function customLogEvent(e:MouseEvent):void {
ta1.text = e.currentTarget.id + ":" + e.type + ":" + e.shiftKey;
// Remove current listener to avoid recursion.
e.currentTarget.removeEventListener("click",customLogEvent);
}
private function handleEvent(e:MouseEvent):void {
// Add new handler for custom event about to be dispatched.
e.currentTarget.addEventListener("click",customLogEvent);
// Create new event object.
var mev:MouseEvent = new MouseEvent("click",false,false);
// Customize event object.
mev.shiftKey = true;
// Dispatch custom event.
e.currentTarget.dispatchEvent(mev);
}
private function addListeners():void {
b1.addEventListener("click",handleEvent);
b2.addEventListener("click",handleEvent);
}
]]></mx:Script>
<mx:VBox id="vb1">
<mx:Button id="b1" label="B1"/>
<mx:Button id="b2" label="B2"/>
<mx:TextArea id="ta1"/>
</mx:VBox>
</mx:Application>
Manually dispatching events 111
If you want to add custom properties to an Event object, you must extend the Event object
and define the new properties in your own custom class. You can then manually dispatch your
custom events with the dispatchEvent() method, as you would any event.
If you create a custom ActionScript class that dispatches its own events but does not extend
UIComponent, you can extend the flash.events.EventDispatcher class to get access to the
addEventListener(), removeEventListener(), and dispatchEvent() methods.
For more information on creating custom classes, see Creating and Extending Flex 2
Components.
Event propagation
When events are triggered, there are three phases in which Flex checks whether there are event
listeners. These phases occur in the following order:
■ First, capturing
■ Next, targeting
■ Finally, bubbling
During each of these phases, the nodes have a chance to react to the event. For example,
assume the user clicks a Button control that is inside a VBox container. During the capturing
phase, Flex checks the Application object and the VBox for listeners to handle the event. Flex
then triggers the Button’s listeners in the target phase. In the bubbling phase, the VBox and
then the Application are again given a chance to handle the event now in the reverse order
from the order in which they were checked in the capturing phase.
In ActionScript 3.0, you can register event listeners on a target node and on any node along
the event flow. Not all events, however, participate in all three phases of the event flow. Some
types of events are dispatched directly to the target node and participate in neither the
capturing nor the bubbling phases. All events can be captured unless they are dispatched from
the top node.
Other events may target objects that are not on the display list, such as events dispatched to an
instance of the Socket class. These event objects flow directly to the target node, without
participating in the capturing or bubbling phases. You can also cancel an event as it flows
through the event model so that even though it was supposed to continue to the other phases,
you stopped it from doing so. You can do this only if the cancelable property is set to true.
112 Using Events
Capturing and bubbling happen as the Event object moves from node to node in the display
list: parent-to-child for capturing and child-to-parent for bubbling. This process has nothing
to do with the inheritance hierarchy. Only DisplayObject objects (visual objects such as
containers and controls) can have a capturing phase and a bubbling phase in addition to the
targeting phase.
Mouse events and keyboard events are among those that bubble. Any event can be captured,
but no DisplayObject objects listen during the capturing phase unless you explicitly instruct
them to do so. In other words, capturing is disabled by default.
When a faceless event dispatcher, such as a Validator, dispatches an event, there is only a
targeting phase, because there is no visual display list for the Event object to capture or bubble
through.
About the target and currentTarget properties
Every Event object has a target and a currentTarget property that help you to keep track
of where it is in the process of propagation. The target property refers to the dispatcher of
the event. The currentTarget property refers to the current node that is being examined for
event listeners.
When you handle a mouse event such as MouseEvent.CLICK by writing a listener on some
component, the event.target property does not necessarily refer to that component; it is
often a subcomponent, such as the Button control’s UITextField, that defines the label.
When Flash Player dispatches an event, it dispatches the event from the frontmost object
under the mouse. Because children are in front of parents, that means it might dispatch the
event from an internal subcomponent, such as the UITextField of a Button.
The event.target property is set to the object that dispatched the event (in this case,
UITextField), not the object that is being listened to (in most cases, you have a Button control
listen for a click event).
MouseEvent events bubble up the parent chain, and can be handled on any ancestor. As the
event bubbles, the value of the event.target property stays the same (UITextField), but the
value of the event.currentTarget property is set at each level to be the ancestor that is
handling the event. Eventually, the currentTarget will be Button, at which time the Button
control’s event listener will handle the event. For this reason, you should use the
event.currentTarget property rather than the event.target property; for example:
<mx:Button label="OK" click="trace(event.currentTarget.label)"/>
In this case, in the Button event’s click event listener, the event.currentTarget property
always refers to the Button, while event.target might be either the Button or its
UITextField, depending on where on the Button control the user clicked.
Event propagation 113
Capturing phase
In the capturing phase, Flex examines an event’s ancestors in the display list to see if which
ones are registered as a listener for the event. Flex starts with the root ancestor and continues
down the display list to the direct ancestor of the target. In most cases, the root ancestors are
the stage, then the SystemManager, then the Application object.
For example, if you have an application with a Panel container that contains a TitleWindow
container, which in turn contains a Button control, the structure appears as follows:
Application
Panel
TitleWindow
Button
If your listener is on the click event of the Button control, the following steps occur during
the capturing phase if capturing is enabled:
1. Check the Application container for click event listeners.
2. Check the Panel container for click event listeners.
3. Check the TitleWindow container for click event listeners.
During the capturing phase, Flex changes the value of the currentTarget property on the
Event object to match the current node whose listener is being called. The target property
continues to refer to the dispatcher of the event.
By default, no container listens during the capturing phase. The default value of the
use_capture argument is false. The only way to add a listener during this phase is to pass
true for the use_capture argument when calling the addEventListener() method, as the
following example shows:
myPanel.addEventListener(MouseEvent.MOUSE_DOWN, clickHandler, true);
If you add an event listener inline with MXML, Flex sets this argument to false; you cannot
override it.
If you set the use_capture argument to true—in other words, if an event is propagated
through the capturing phase—the event can still bubble, but capture phase listeners will not
react to it. If you want your event to traverse both the capturing and bubbling phases, you
must call addEventListener() twice: once with use_capture set to true, and then again
with use_capture set to false.
The capturing phase is very rarely used, and it can also be computationally intensive. By
contrast, bubbling is much more common.
114 Using Events
Targeting phase
In the targeting phase, Flex invokes the event dispatcher’s listeners. No other nodes on the
display list are examined for event listeners. The values of the currentTarget and the target
properties on the Event object during the targeting phase are the same.
Bubbling phase
In the bubbling phase, Flex examines an event’s ancestors for event listeners. Flex starts with
the dispatcher’s immediate ancestor and continues up the display list to the root ancestor. This
is the reverse of the capturing phase.
For example, if you have an application with a Panel container that contains a TitleWindow
container that contains a Button control, the structure appears as follows:
Application
Panel
TitleWindow
Button
If your listener is on the click event of the Button control, the following steps occur during
the bubble phase if bubbling is enabled:
1. Check the TitleWindow container for click event listeners.
2. Check the Panel container for click event listeners.
3. Check the Application container for click event listeners.
An event only bubbles if its bubbles property is set to true. Mouse events and keyboard
events are among those that bubble; it is less common for higher-level events that are
dispatched by Flex to bubble. Events that can be bubbled include change, click,
doubleClick, keyDown, keyUp, mouseDown, and mouseUp. To determine whether an event
bubbles, see the event’s entry in Adobe Flex 2 Language Reference.
During the bubbling phase, Flex changes the value of the currentTarget property on the
Event object to match the current node whose listener is being called. The target property
continues to refer to the dispatcher of the event.
When Flex invokes an event listener, the Event object might have actually been dispatched by
an object deeper in the display list. The object that originally dispatched the event is the
target. The object that the event is currently bubbling through is the currentTarget. So,
you should generally use the currentTarget property instead of the target property when
referring to the current object in your event listeners.
Event propagation 115
You can only register an event listener with an object if that object dispatches the event. For
example, you cannot register a Form container to listen for a click event, even though that
container contains a Button control. Form containers do not dispatch click events. Form
containers do dispatch the mouseDown event, so you could put a mouseDown event listener on
the Form container tag. If you do that, your event listener is triggered whenever the Button
control or Form container receives a mouseDown event.
If you set the useCapture property to true—in other words, if an event is propagated
through the capturing phase—then it does not bubble, regardless of its default bubbling
behavior. If you want your event to traverse both the capturing and bubbling phases, you
must call addEventListener() twice: once with useCapture set to true, and then again
with useCapture set to false.
An event only bubbles up the parent’s chain of ancestors in the display list. Siblings, such as
two Button controls inside the same container, do not intercept each other’s events.
Detecting the event phase
You can determine what phase you are in by using the Event object’s eventPhase property.
This property contains an integer that represents one of the following constants:
■ 1 — Capturing phase (CAPTURING_PHASE)
■ 2 — Targeting phase (AT_TARGET)
■ 3 — Bubbling phase (BUBBLING_PHASE)
The following example displays the current phase and current target’s ID:
<?xml version="1.0"?>
<!-- events/DisplayCurrentTargetInfo.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
private function showInfo(e:MouseEvent):void {
trace(e.eventPhase + ":" + e.currentTarget.id);
}
]]></mx:Script>
<mx:Button id="b1" label="Click Me" click="showInfo(event)"/>
</mx:Application>
Stopping propagation
During any phase, you can stop the traversal of the display list by calling one of the following
methods on the Event object:
■ stopPropagation()
■ stopImmediatePropagation()
116 Using Events
You can call either the event’s stopPropagation() method or the
stopImmediatePropagation() method to prevent an Event object from continuing on its
way through the event flow. The two methods are nearly identical and differ only in whether
the current node’s remaining event listeners are allowed to execute. The stopPropagation()
method prevents the Event object from moving on to the next node, but only after any other
event listeners on the current node are allowed to execute.
The stopImmediatePropagation() method also prevents the Event objects from moving on
to the next node, but it does not allow any other event listeners on the current node to
execute.
The following example creates a TitleWindow container inside a Panel container. Both
containers are registered to listen for a mouseDown event. As a result, if you click on the
TitleWindow container, the showAlert() method is called twice unless you add a call to the
stopImmediatePropagation() method, as the following example shows:
<?xml version="1.0"?>
<!-- events/StoppingPropagation.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="init(event)">
<mx:Script><![CDATA[
import mx.controls.Alert;
import flash.events.MouseEvent;
import flash.events.Event;
public function init(e:Event):void {
p1.addEventListener(MouseEvent.MOUSE_DOWN,showAlert);
tw1.addEventListener(MouseEvent.MOUSE_DOWN,showAlert);
tw1.addEventListener(Event.CLOSE,closeWindow);
}
public function showAlert(e:Event):void {
Alert.show("Alert!\n" + e.currentTarget + "\n" + e.eventPhase);
e.stopImmediatePropagation();
}
public function closeWindow(e:Event):void {
p1.removeChild(tw1);
}
]]></mx:Script>
<mx:Panel id="p1" title="Panel 1">
<mx:TitleWindow id="tw1" width="300" height="300"
showCloseButton="true" title="Title Window 1">
<mx:Button label="Enter name"/>
<mx:TextArea id="ta1"/>
</mx:TitleWindow>
</mx:Panel>
</mx:Application>
Event propagation 117
Examples
In the following example, the parent container’s click handler disables the target control after
the target handles the event. It shows that you can reuse the logic of a single listener (click on
the HBox container) for multiple events (all the clicks).
<?xml version="1.0"?>
<!-- events/NestedHandlers.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
public function disableControl(event:MouseEvent):void {
event.currentTarget.enabled = false;
}
public function doSomething(event:MouseEvent):void {
b1.label = "clicked";
ta1.text += "something wonderful happened";
}
public function doSomethingElse(event:MouseEvent):void {
b2.label = "clicked";
ta1.text += "something wonderful happened again";
}
]]></mx:Script>
<mx:HBox height="50" click="disableControl(event)">
<mx:Button id='b1' label="Click Me" click="doSomething(event)"/>
<mx:Button id='b2' label="Click Me" click="doSomethingElse(event)"/>
<mx:TextArea id="ta1"/>
</mx:HBox>
</mx:Application>
By having a single listener on a parent control instead of many listeners (one on each child
control), you can reduce your code size and make your applications more efficient. Reducing
the amount of calls to the addEventListener() method potentially reduces application
startup time and memory usage.
118 Using Events
The following example registers an event handler for the Panel container, rather than
registering a listener for each link. All children of the Panel container inherit this event
handler. Since Flex invokes the handler on a bubbled event, you use the target property
rather than the currentTarget property. In this handler, the currentTarget property would
refer to the Panel control, whereas the target property refers to the LinkButton control,
which has the label that you want.
<?xml version="1.0"?>
<!-- events/SingleRegisterHandler.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="createLinkHandler()">
<mx:Script><![CDATA[
private function linkHandler(event:MouseEvent):void {
var url:URLRequest = new URLRequest("http://finance.google.com/
finance?q=" + event.target.label);
navigateToURL(url);
}
private function createLinkHandler():void {
p1.addEventListener(MouseEvent.CLICK,linkHandler);
}
]]></mx:Script>
<mx:Panel id="p1" title="Click on a stock ticker symbol">
<mx:LinkButton label="ADBE"/>
<mx:LinkButton label="GE"/>
<mx:LinkButton label="IBM"/>
<mx:LinkButton label="INTC"/>
</mx:Panel>
</mx:Application>
Event priorities
You can register any number of event listeners with a single event. Flex registers event listeners
in the order in which the addEventListener() methods are called. Flex then calls the
listener functions when the event occurs in the order in which they were registered. However,
if you register some event listeners inline and some with the addEventListener() method,
the order in which the listeners are called for a single event can be unpredictable.
You can change the order in which Flex calls event listeners by using the priority parameter
of the addEventListener() method. It is the fourth argument of the addEventListener()
method.
Event priorities 119
Flex calls event listeners in priority order, from highest to lowest. The highest priority event is
called first. In the following example, Flex calls the verifyInputData() method before the
saveInputData() function. The verifyInputData() method has the highest priority. The
last method to be called is returnResult() because the value of its priority parameter is
lowest.
<?xml version="1.0"?>
<!-- events/ShowEventPriorities.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="initApp()">
<mx:Script><![CDATA[
private function returnResult(e:Event):void {
trace("returnResult");
}
private function verifyInputData(e:Event):void {
trace("verifyInputData");
}
private function saveInputData(e:Event):void {
trace("saveInputData");
}
private function initApp():void {
b1.addEventListener(MouseEvent.CLICK, returnResult, false, 1);
b1.addEventListener(MouseEvent.CLICK, saveInputData, false, 2);
b1.addEventListener(MouseEvent.CLICK, verifyInputData, false, 3);
}
]]></mx:Script>
<mx:Button id="b1" label="Click Me"/>
</mx:Application>
You can set the event priority to any valid integer, positive or negative. The default value is 0.
If multiple listeners have the same priority, Flex calls them in the order in which they were
registered.
If you want to change the priority of an event listener once the event listener has already been
defined, you must remove the listener by calling the removeEventListener() method. You
add the event again with the new priority.
The priority parameter of the addEventListener() method is not an official part of the
DOM Level 3 events model. ActionScript 3.0 provides it so that programmers can be more
flexible when organizing their event listeners.
120 Using Events
Even if you give a listener a higher priority than other listeners, there is no way to guarantee
that the listener will finish executing before the next listener is called. You should ensure that
listeners do not rely on other listeners completing execution before calling the next listener. It
is important to understand that Flash Player does not necessarily wait until the first event
listener finishes processing before proceeding with the next one.
If your listeners do rely on each other, you can call one listener function from within another,
or dispatch a new event from within the first event listener. For more information on
manually dispatching events, see “Manually dispatching events” on page 109.
Using event subclasses
Depending on the event type, the Event object can have a wide range of properties. These
properties are based on those defined in the W3C specification (www.w3.org/TR/DOM-
Level-3-Events/events.html), but Flex does not implement all of these.
When you declare an Event object in a listener function, you can declare it of type Event, or
you can specify a subclass of the Event object. In the following example, you specify the event
object as type MouseEvent:
public function performAction(e:MouseEvent):void {
...
}
Most controls generate an object that is of a specific event type; for example, a mouse click
generates an object of type MouseEvent. By specifying a more specific event type, you can
access specific properties without having to cast the Event object to something else. In
addition, some subclasses of the Event object have methods that are unique to them. For
example, the LogEvent has a getLevelString() method, which returns the log level as a
String. The generic Event object does not have this method.
Using event subclasses 121
An event object that you define at run time can be a subclass of the compile-time type. You
can access the event-specific properties inside an event listener even if you did not declare the
specific event type, as long as you cast the Event object to a specific type. In the following
example, the function defines the object type Event. However, inside the function, in order to
access the localX and localY properties, which are specific to the MouseEvent class, you
must cast the Event object to be of type MouseEvent.
<?xml version="1.0"?>
<!-- events/AccessEventSpecificProperties.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="addListeners()">
<mx:Script><![CDATA[
private function customLogEvent(e:Event):void {
var a:MouseEvent = MouseEvent(e);
trace(a.localY + ":" + a.localX);
}
private function addListeners():void {
b1.addEventListener(MouseEvent.CLICK, customLogEvent);
}
]]></mx:Script>
<mx:VBox id="vb1">
<mx:Button id="b1" label="Click Me"/>
</mx:VBox>
</mx:Application>
If you declare the Event object as a specific type, you are not required to cast that object in the
handler, as the following example shows:
private function customLogEvent(e:MouseEvent):void { ... }
122 Using Events
In the previous example, you can also cast the Event object for only the property access, using
the syntax shown in the following example:
<?xml version="1.0"?>
<!-- events/SinglePropertyAccess.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="addListeners()">
<mx:Script><![CDATA[
private function customLogEvent(e:Event):void {
trace(MouseEvent(e).localY + ":" + MouseEvent(e).localX);
}
private function addListeners():void {
b1.addEventListener(MouseEvent.CLICK, customLogEvent);
}
]]></mx:Script>
<mx:VBox id="vb1">
<mx:Button id="b1" label="Click Me"/>
</mx:VBox>
</mx:Application>
This approach can use less memory and system resources, but it is best to declare the event’s
type as specifically as possible.
Each of the Event object’s subclasses provides additional properties and event types that are
unique to that category of events. The MouseEvent class defines several event types related to
that input device, including the CLICK, DOUBLE_CLICK, MOUSE_DOWN, and MOUSE_UP event
types.
For a list of types for each Event subclass, see the subclass’s entry in Adobe Flex 2 Language
Reference.
About keyboard events
It is common for applications to respond to a key or series of keys and perform some action—
for example, Control+q to quit the application. While Flash Player supports all the basic
functionality of key combinations from the underlying operating system, it also lets you
override or trap any key or combination of keys to perform a custom action.
Handling keyboard events
In some cases, you want to trap keys globally, meaning no matter where the user is in the
application, their keystrokes are recognized by the application and the action is performed.
Flex recognizes global keyboard events whether the user is hovering over a button or the focus
is inside a TextInput control.
About keyboard events 123
A common way to handle global key presses is to create a listener for the
KeyboardEvent.KEY_DOWN or KeyboardEvent.KEY_UP event on the application.
Listeners on the application container are triggered every time a key is pressed, regardless of
where the focus is. Inside the handler, you can examine the key code or the character code
using the charCode and keyCode properties of the KeyboardEvent class, as the following
example shows:
<?xml version="1.0"?>
<!-- events/TrapAllKeys.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="initApp()">
<mx:Script><![CDATA[
private function initApp():void {
application.addEventListener(KeyboardEvent.KEY_UP,keyHandler);
// Set the focus somewhere inside the application.
myCanvas.setFocus();
}
// Quit the application by closing the browser using JavaScript
// if the user presses Shift+Q. This may not work in all browsers.
private function keyHandler(event:KeyboardEvent):void {
trace(event.keyCode + "/" + event.charCode);
var url:URLRequest = new URLRequest("javascript:window.close()");
navigateToURL(url,"_self");
}
]]></mx:Script>
<mx:Canvas id="myCanvas"/>
</mx:Application>
124 Using Events
Because any class that extends UIComponent dispatches the keyUp and keyDown events, you
can also trap keys pressed when the focus is on an individual component, as in the following
example:
<?xml version="1.0"?>
<!-- events/TrapKeysOnTextArea.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
private function keyHandler(event:KeyboardEvent):void {
trace(event.keyCode + "/" + event.charCode);
}
]]></mx:Script>
<mx:TextInput id="my_input" keyUp="keyHandler(event)"/>
</mx:Application>
Understanding the keyCode and charCode properties
You can access the keyCode and charCode properties to determine what key was pressed and
trigger other actions as a result. The keyCode property is a numeric value that corresponds to
the value of a key on the keyboard. The charCode property is the numeric value of that key in
the current character set (the default character set is UTF-8, which supports ASCII). The
primary difference between the key code and character values is that a key code value
represents a particular key on the keyboard (the 1 on a keypad is different than the 1 in the
top row, but the 1 on the keyboard and the key that generates the ! are the same key), and the
character value represents a particular character (the R and r characters are different).
The mappings between keys and key codes is device and operating system dependent. ASCII
values, on the other hand, are available in the ActionScript documentation.
The following example shows the character and key code values for the keys you press. When
you run this example, you must be sure to put the focus in the application before beginning.
<?xml version="1.0"?>
<!-- charts/ShowCharAndKeyCodes.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="init()">
<mx:Script><![CDATA[
import flash.events.KeyboardEvent;
private function init():void {
ti1.setFocus();
this.addEventListener(KeyboardEvent.KEY_DOWN, trapKeys);
}
private function trapKeys(e:KeyboardEvent):void {
l0.text = String(e.toString());
About keyboard events 125
l1.text = numToChar(e.charCode) + " (" + String(e.charCode) + ")";
l2.text = numToChar(e.keyCode) + " (" + String(e.keyCode) + ")";
}
private function numToChar(num:int):String {
if (num > 47 && num < 58) {
var strNums:String = "0123456789";
return strNums.charAt(num - 48);
} else if (num > 64 && num < 91) {
var strCaps:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
return strCaps.charAt(num - 65);
} else if (num > 96 && num < 123) {
var strLow:String = "abcdefghijklmnopqrstuvwxyz";
return strLow.charAt(num - 97);
} else {
return num.toString();
}
}
]]></mx:Script>
<mx:TextInput width="50%" id="ti1"/>
<mx:Canvas id="mainCanvas" width="100%" height="100%">
<mx:Form>
<mx:FormItem label="Char (Code)">
<mx:Label id="l1"/>
</mx:FormItem>
<mx:FormItem label="Key (Code)">
<mx:Label id="l2"/>
</mx:FormItem>
<mx:FormItem label="Key Event">
<mx:Label id="l0"/>
</mx:FormItem>
</mx:Form>
</mx:Canvas>
</mx:Application>
126 Using Events
You can listen for specific keys or combinations of keys by using a conditional operator in the
KeyboardEvent handler. The following example listens for the combination of the Shift key
plus the q key and prompts the user to close the browser window if they press those keys at the
same time:
<?xml version="1.0"?>
<!-- events/TrapQKey.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="initApp()">
<mx:Script><![CDATA[
private function initApp():void {
application.addEventListener(KeyboardEvent.KEY_UP,keyHandler);
// Set the focus somewhere inside the application.
myCanvas.setFocus();
}
//This function quits the application if the user presses Shift+Q.
private function keyHandler(event:KeyboardEvent):void {
var bShiftPressed:Boolean = event.shiftKey;
if (bShiftPressed) {
var curKeyCode:int = event.keyCode;
if (curKeyCode == 81) { // 81 is the keycode value for the Q key
// Quit the application by closing the browser using JavaScript.
// This may not work in all browsers.
var url:URLRequest = new
URLRequest("javascript:window.close()");
navigateToURL(url,"_self");
}
}
}
]]></mx:Script>
<mx:Canvas id="myCanvas"/>
</mx:Application>
Notice that this application must have focus when you run it in a browser so that the
application can capture keyboard events.
Understanding KeyboardEvent precedence
If you define keyUp or keyDown event listeners for both a control and its parent, you will
notice that the keyboard event is dispatched for each component because the event bubbles.
The only difference is that the currentTarget property of the KeyboardEvent object is
changed.
About keyboard events 127
In the following example, the application, the my_vbox container, and the my_textinput
control all dispatch keyUp events to the keyHandler() event listener function:
<?xml version="1.0"?>
<!-- events/KeyboardEventPrecedence.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="initApp()">
<mx:Script><![CDATA[
private function initApp():void {
application.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
my_vbox.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
my_textinput.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
// Set the focus somewhere inside the application.
my_textinput.setFocus();
}
private function keyHandler(event:KeyboardEvent):void {
trace(event.target + "(" + event.currentTarget + "): " +
event.keyCode + "/" + event.charCode);
}
]]></mx:Script>
<mx:VBox id="my_vbox">
<mx:TextInput id="my_textinput"/>
</mx:VBox>
</mx:Application>
When you examine the trace() method output, you will notice that the target property of
the KeyboardEvent object stays the same because it refers to the original dispatcher of the
event (in this case, my_textinput). But the currentTarget property changes depending on
what the current node is during the bubbling (in this case, it changes from my_textinput to
my_vbox to the application itself ).
The order of calls to the event listener is determined by the object hierarchy and not the order
in which the addEventListener() methods were called. Child controls dispatch events
before their parents. In this example, for each key pressed, the TextInput control dispatches
the event first, the VBox container next, and finally the application.
When handling a key or key combination that the underlying operating system or browser
recognizes, the operating system or browser generally processes the event first. For example, in
Microsoft Internet Explorer, pressing Control+w closes the browser window. If you trap that
combination in your Flex application, Internet Explorer users never know it, because the
browser closes before the ActiveX Flash Player has a chance to react to the event.
128 Using Events
Handling keyboard-related MouseEvents
The MouseEvent class and all MouseEvent subclasses (such as ChartItemEvent, DragEvent,
ItemClickEvent, and LegendMouseEvent) have the following properties that you can use to
determine if a specific key was held down when the event occurred:
Property Description
altKey Is set to true if the Alt key was held down when the user pressed the mouse
button; otherwise, false.
ctrlKey Is set to true if the Control key was held down when the user pressed
mouse button; otherwise, false.
shiftKey Is set to true if the Shift key was held down when the user pressed mouse
button; otherwise, false.
The following example deletes button controls, based on whether the user holds down the
Shift key while pressing the mouse button:
<?xml version="1.0"?>
<!-- events/DetectingShiftClicks.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="initApp()">
<mx:Script><![CDATA[
import mx.controls.Button;
private function initApp():void {
var b1:Button = new Button();
var b2:Button = new Button();
b1.addEventListener(MouseEvent.CLICK, removeButtons);
b2.addEventListener(MouseEvent.CLICK, removeButtons);
addChild(b1);
addChild(b2);
}
private function removeButtons(event:MouseEvent):void {
if (event.shiftKey) {
removeChild(Button(event.currentTarget));
} else {
event.currentTarget.toolTip = "You must hold the shiftkey down to
delete this button.";
}
}
]]></mx:Script>
</mx:Application>
About keyboard events 129
130 Using Events
PART 2
Building User Interfaces for
Flex Applications 2
This part describes how to use Adobe Flex 2 components to build the user
interface for your application.
The following topics are included:
Chapter 6: Using Flex Visual Components . . . . . . . . . . . . . . . . . . . 133
Chapter 7: Using Data Providers and Collections . . . . . . . . . . . . . 161
Chapter 8: Sizing and Positioning Components . . . . . . . . . . . . . . 221
Chapter 9: Using Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
Chapter 10: Using Text Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
Chapter 11: Using Menu-Based Controls. . . . . . . . . . . . . . . . . . . . 407
Chapter 12: Using Data-Driven Controls. . . . . . . . . . . . . . . . . . . . 439
Chapter 13: Introducing Containers . . . . . . . . . . . . . . . . . . . . . . . . . 491
Chapter 14: Using the Application Container . . . . . . . . . . . . . . . . 529
Chapter 15: Using Layout Containers . . . . . . . . . . . . . . . . . . . . . . 553
Chapter 16: Using Navigator Containers . . . . . . . . . . . . . . . . . . . . 627
131
CHAPTER 6
Using Flex Visual
Components
6
You use visual components to build Adobe Flex applications. Visual components (often
referred to as components for brevity) have a flexible set of characteristics that let you control
and configure them as necessary to meet your application’s requirements. This topic provides
an overview of components, component syntax, and component configuration.
Contents
About visual components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Class hierarchy for visual components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Using the UIComponent class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Sizing visual components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .141
Handling events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Using styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .151
Using behaviors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Applying skins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Changing the appearance of a component at run time . . . . . . . . . . . . . . . . . . . . . . . 155
Extending components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
About visual components
Flex includes a component-based development model that you use to develop your
application and its user interface. You can use the prebuilt visual components included with
Flex, you can extend components to add new properties and methods, and you can create
components as required by your application.
Visual components are extremely flexible and provide you with a great deal of control over the
component’s appearance, how the component responds to user interactions, the font and size
of any text included in the component, the size of the component in the application, and
many other characteristics.
133
This topic contains an overview of many of the characteristics of visual components,
including the following:
Size Height and width of a component. All visual components have a default size. You can
use the default size, specify your own size, or let Flex resize a component as part of laying out
your application.
Events Application or user actions that require a component response. Events include
component creation, mouse actions such as moving the mouse over a component, and button
clicks.
Styles Characteristics such as font, font size, and text alignment. These are the same styles
that you define and use with Cascading Style Sheets (CSS).
Behaviors Visible or audible changes to the component triggered by an application or user
action. Examples of behaviors are moving or resizing a component based on a mouse click.
Skins Classes that control a visual component’s appearance.
Class hierarchy for visual components
Flex visual components are implemented as a class hierarchy in ActionScript. Therefore, each
visual component in your application is an instance of an ActionScript class. The following
image shows this hierarchy in detail up to the Flash Sprite component level:
Object
EventDispatcher
DisplayObject
InteractiveObject
DisplayObjectContainer
Sprite
UIComponent
All components
134 Using Flex Visual Components
All visual components are derived from the UIComponent class and its superclasses, the Flash
Sprite through Object classes, and inherit the properties and methods of their superclasses. In
addition, visual components inherit other characteristics of the superclasses, including event,
style, and behavior definitions.
Using the UIComponent class
The UIComponent class is the base class for all Flex visual components. For detailed
documentation, see UIComponent in Adobe Flex 2 Language Reference.
Commonly used UIComponent properties
The following table lists only the most commonly used properties of components that extend
the UIComponent class:
Property Type Description
doubleClickEnabled Boolean Setting to true lets the component dispatch a
doubleClickEvent when a user presses and releases the mouse
button twice in rapid succession over the component.
enabled Boolean Setting to true lets the component accept keyboard focus and
mouse input. The default value is true.
If you set enabled to false for a container, Flex dims the color
of the container and all of its children, and blocks user input to
the container and to all its children.
height Number The height of the component, in pixels.
In MXML tags, but not in ActionScript, you can set this
property as a percentage of available space by specifying a
value such as 70%; in ActionScript, you must use the
percentHeight property.
The property always returns a number of pixels. In
ActionScript, you use the perCent
id String Specifies the component identifier. This value identifies the
specific instance of the object and should not contain any
white space or special characters. Each component in a Flex
document must have a unique id value. For example, if you
have two custom components, each component can include
one, and only one Button control with the id "okButton".
Using the UIComponent class 135
Property Type Description
percentHeight Number The height of the component as a percentage of its parent
container, or for <mx:Application> tags, the full height of the
browser. Returns NaN if a percent-based width has never been
set or if a width property was set after the percentWidth was
set.
percentWidth Number The width of the component as a percentage of its parent
container, or for <mx:Application> tags, the full span of the
browser. Returns NaN if a percent-based width has never been
set or if a width property was set after the percentWidth was
set.
styleName String Specifies the style class selector to apply to the component.
toolTip String Specifies the text string displayed when the mouse pointer
hovers over that component.
visible Boolean Specifies whether the container is visible or invisible. The
default value is true, which specifies that the container is
visible.
width Number The width of the component, in pixels.
In MXML tags, but not in ActionScript, you can set this
property as a percentage of available space by specifying a
value such as 70%; in ActionScript, you must use the
percentWidth property.
The property always returns a number of pixels.
x Number The component’s x position within its parent container.
Setting this property directly has an effect only if the parent
container uses absolute positioning.
y Number The component’s y position within its parent container. Setting
this property directly has an effect only if the parent container
uses absolute positioning.
Using components in MXML and ActionScript
Every Flex component has an MXML API and an ActionScript API. A component’s MXML
tag attributes are equivalent to its ActionScript properties, styles, behaviors, and events. You
can use both MXML and ActionScript when working with components.
136 Using Flex Visual Components
To configure a component:
1. Set the value of a component property, event, style, or behavior declaratively in an MXML
tag, or at run time in ActionScript code.
2. Call a component’s methods at run time in ActionScript code. The methods of an
ActionScript class are not exposed in the MXML API.
The following example creates a Button control in MXML. When the user clicks the Button
control, it updates the text of a TextArea control by using an ActionScript function.
<?xml version="1.0"?>
<!-- components\ButtonApp.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
public function handleClick():void {
text1.text="Thanks for the click!";
}
]]>
</mx:Script>
<mx:Button id="button1"
label="Click here!"
width="100"
fontSize="12"
click="handleClick();"/>
<mx:TextArea id="text1"/>
</mx:Application>
This example has the following elements:
■ The id property is inherited by the Button control from the UIComponent class. You use
it to specify an identifier for the component. This property is optional, but you must
specify it if you want to access the component in ActionScript.
■ The label property is defined by the Button control. It specifies the text that appears in
the button.
■ The width property is inherited from the UIComponent class. It optionally specifies the
width of the button, in pixels.
■ The Button control dispatches a click event when the user when a user presses and
releases the main mouse button. The MXML click attribute specifies the ActionScript
code to execute in response to the event.
■ The fontSize style is inherited from the UIComponent class. It specifies the font size of
the label text, in pixels.
Using the UIComponent class 137
The click event attribute can also take ActionScript code directly as its value, without your
having to specify it in a function. Therefore, you can rewrite this example as the following
code shows:
<?xml version="1.0"?>
<!-- components\ButtonAppAS.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Button id="button1"
label="Click here!"
width="100"
fontSize="12"
click="text1.text='Thanks for the click!';"/>
<mx:TextArea id="text1"/>
</mx:Application>
Both of these examples result in the following image, shown after the button was clicked:
Although you can specify multiple lines of ActionScript code, separated by semicolons,
NO T E
as the value of the click event attribute, for readability you should limit the click event to
only one or two lines of code.
Initializing components at run time
Flex uses MXML property attributes to initialize your components. However, you might want
to use some logic to determine initial values at run time. For example, you might want to
initialize a component with the current date or time. Flex must calculate this type of
information when the application executes.
Every component dispatches several events during its life cycle. In particular, all components
dispatch the following events that let you specify ActionScript to initialize a component:
preInitialize Dispatched when a component has been created in a rough state, and any
children have not been created.
initialize
Dispatched when a component and all its children have been created, but before
the component size has been determined.
138 Using Flex Visual Components
creationComplete Dispatched when the component has been laid out and the component
is visible (if appropriate).
For more information on how components are created, see “About the component
NO T E
instantiation life cycle” on page 149.
You can use the initialize event to configure most component characteristics; in particular,
use it to configure any value that affects the component’s size. Use the creationComplete
event if your initialization code must get information about the component layout.
The following example configures Flex to call the initDate() function when it initializes the
Label control. When Flex finishes initializing the Label control, and before the application
appears, Flex calls the initDate() function.
<?xml version="1.0"?>
<!-- components\LabelInit.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
private function initDate():void {
label1.text += new Date();
}
]]>
</mx:Script>
<mx:Box borderStyle="solid">
<mx:Label id="label1"
text="Today's Date: "
initialize="initDate();"/>
</mx:Box>
</mx:Application>
This example produces the following image:
Using the UIComponent class 139
You can also express the previous example without a function call by adding the ActionScript
code in the component’s definition. The following example does the same thing, but without
an explicit function call:
<?xml version="1.0"?>
<!-- components\LabelInitAS.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Box borderStyle="solid">
<mx:Label id="label1"
text="Today's Date:"
initialize="label1.text += new Date();"/>
</mx:Box>
</mx:Application>
As with other calls that are embedded within component definitions, you can add multiple
ActionScript statements to the initialize MXML attribute by separating each function or
method call with a semicolon. The following example calls the initDate() function and
writes a message in the flexlog.txt file when the label1 component is instantiated:
<?xml version="1.0"?>
<!-- components\LabelInitASAndEvent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
private function initDate():void {
label1.text += new Date();
}
]]>
</mx:Script>
<mx:Box borderStyle="solid">
<mx:Label id="label1"
text="Today's Date:"
initialize="initDate(); trace('The label is initialized!');"/>
</mx:Box>
</mx:Application>
140 Using Flex Visual Components
Configuring components: syntax summary
The following table summarizes the MXML and ActionScript component APIs that you use
to configure components:
MXML example ActionScript example
Read- <mx:Tile id="tile1" tile1.label="My Tile";
label="My Tile" tile1.visible=true;
write
visible="true"/>
property
Read-only You cannot use a read-only To get the value of a read-only property:
property property as an attribute in MXML. var theClass:String=mp1.className;
Method Methods are not available in myList.sortItemsBy("data", "DESC");
MXML.
Event <mx:Accordion id="myAcc" private function
change="changeHandler changeHandler(event:MouseEvent):void {
(event);"/> ...
}
(You must also define a
changeHandler() function as shown myButton.addEventListener("click",
changeHandler);
in the ActionScript example.
Style <mx:Tile id="tile1" To set the style:
paddingTop="12" tile1.setStyle("paddingTop", 12);
paddingBottom="12"/>
tile1.setStyle("paddingBottom", 12);
To get the style:
var currentPaddingTop:Number =
tile1.getStyle("paddingTop");.
Behavior <mx:Tile id="tile1" To set the behavior:
showEffect="{AWipeEffect}"/>
myButton.setStyle('showEffect',
AWipeEffect);
To get the behavior:
var currentShowEffect:String =
tile1.getStyle("showEffect");
Sizing visual components
The Flex sizing and layout mechanisms provide several ways for you to control the size of
visual components:
Default sizing Flex automatically determines the sizes of controls and containers. To use
default sizing, you do not specify the component’s dimensions or layout constraints.
Sizing visual components 141
Explicit sizing You set the height and width properties to pixel values. When you do this,
you set the component dimension to absolute sizes, and Flex does not override these values.
The following <mx:Application> tag, for example, sets explicit Application dimensions:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
height="300"
width="600">
Percentage-based sizing You specify the component size as a percentage of its container
size. To do this, you specify the percentHeight and percentWidth properties, or, in an
MXML tag, set the height and width properties to percentage values such as 100%. The
following code, for example, sets percentage-based dimensions for an HBox container:
<mx:HBox id="hBox1" xmlns:mx="http://www.adobe.com/2006/mxml"
height="30%"
width="90%"/>
The following ActionScript line resets the HBox width to a different percentage value:
hBox1.percentWidth=40;
Constraint-based layout You can control size and position by anchoring components sides
or centers to locations in their container by specifying the top, bottom, left, right,
horizontalCenter, and verticalCenter styles. You can use constraint-based layout only
for the children of a container that uses absolute layout; the Application and Panel containers
can optionally use this layout, and the Canvas container always uses it. The following example
uses constraint-based layout to position an HBox horizontally, and explicit sizing and
positioning to determine the vertical width and position:
<mx:HBox id="hBox2" xmlns:mx="http://www.adobe.com/2006/mxml"
left="30"
right="30"
y="150"
height="100"/>
You can mix sizing techniques; however, you must ensure that the mix is appropriate. Do not
specify more than one type of sizing for a component dimension; for example, do not specify
a height and a percentHeight for a component. Also, ensure that the resulting sizes are
appropriate; for example, if you do not want scroll bars or clipped components, ensure that
the sizes of a container’s children do not exceed the container size.
For detailed information on how Flex sizes components, and how you can specify sizing, see
Chapter 8, “Sizing and Positioning Components,” on page 221.
142 Using Flex Visual Components
Examples of component sizing
The following example shows sizing within an explicitly sized container when some of the
container’s child controls are specified with explicit widths and some with percentage-based
widths. It shows the flexibility and the complexities involved in determining component sizes.
The application logs the component sizes to flashlog.txt, so you can confirm the sizing
behavior.
<?xml version="1.0"?>
<!-- components\CompSizing.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="logSizes();">
<mx:Script>
<![CDATA[
private function logSizes():void {
trace("HBox: "+ hb1.width);
trace("Label: "+ lb1.width);
trace("Image: "+ img1.width);
trace("Button: "+ b1.width);
}
]]>
</mx:Script>
<mx:HBox id="hb1" width="250">
<mx:Label id="lb1"
text="Hello"
width="50"/>
<mx:Image id="img1"
source="@Embed(source='assets/flexlogo.jpg')"
width="75%"/>
<mx:Button id="b1"
label="Button"
width="25%"/>
</mx:HBox>
</mx:Application>
The application consists of a 250-pixel-wide HBox container that contains a 50-pixel-wide
label, an image that requests 75% of the container width, and a button that requests 25% of
the container width. The component sizes are determined as follows:
1. Flex reserves 50 pixels for the explicitly sized Label control.
2. Flex puts an 8-pixel gap between components by default, so it reserves 16 pixels for the
gaps; this leaves 184 pixels available for the two percentage-based components.
Sizing visual components 143
3. The minimum width of the Button component, if you do not specify an explicit width, fits
the label text plus padding around it. In this case, the minimum size is 65 pixels. This value
is larger than 25% of the component, so Flex does not use the percentage request, and
reserves 65 pixels for the Button control.
4. The percentage-based image requests 75% of 250 pixels, or 187 pixels, but the available
space is only 119 pixels, which it takes.
If you change the button and image size properties to 50%, the minimum button size is
smaller than the requested size, so the percentage-sized controls each get 50% of the available
space, 92 pixels.
The following example uses explicit sizing for the Image control and default sizing for the
Button control and yields the same results as the initial example:
<?xml version="1.0"?>
<!-- components\CompSizingExplicit.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="logSizes();">
<mx:Script>
<![CDATA[
private function logSizes():void {
trace("HBox: "+ hb1.width);
trace("Label: "+ lb1.width);
trace("Image: "+ img1.width);
trace("Button: "+ b1.width);
}
]]>
</mx:Script>
<mx:HBox id="hb1" width="250">
<mx:Label id="lb1"
text="Hello"
width="50"/>
<mx:Image id="img1"
source="@Embed(source='assets/flexlogo.jpg')"
width="119" />
<mx:Button id="b1"
label="Button"/>
</mx:HBox>
</mx:Application>
144 Using Flex Visual Components
Percentage-based sizing removes the need to explicitly consider the gaps and margins of a
container in sizing calculations, but its greatest benefit applies when containers resize. Then,
the percentage-based children resize automatically based on the available container size. In the
following example, the series of controls on the left resize as you resize your browser, but the
corresponding controls on the right remain a fixed size because their container is fixed. Click
the first Button control to logs the component sizes to flashlog.txt.
<?xml version="1.0"?>
<!-- components\CompSizingPercent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
private function logSizes():void {
trace("HBox: "+ hb1.width);
trace("Label: "+ lb1.width);
trace("Image: "+ img1.width);
trace("Button: "+ b1.width);
}
]]>
</mx:Script>
<mx:HBox width="100%">
<mx:HBox id="hb1" width="40%" borderStyle="solid">
<mx:Label id="lb1"
text="Hello"
width="50"/>
<mx:Image id="img1"
source="@Embed(source='assets/flexlogo.jpg')"
width="60%"/>
<mx:Button id="b1"
label="Button"
width="40%"
click="logSizes();"/>
</mx:HBox>
<mx:HBox width="260" borderStyle="solid">
<mx:Label
text="Hello"
width="50"/>
<mx:Image
source="@Embed(source='assets/flexlogo.jpg')"
width="119" />
<mx:Button
label="Button"/>
</mx:HBox>
</mx:HBox>
</mx:Application>
For more information about sizing considerations, see “Sizing components” on page 228.
Sizing visual components 145
Handling events
Flex applications are event-driven. Events let a programmer know when the user has interacted
with an interface component, and also when important changes have happened in the
appearance or life cycle of a component, such as the creation or destruction of a component or
its resizing.
When an instance of a component dispatches an event, objects that have registered as listeners
for that event are notified. You define event listeners, also called event handlers, in
ActionScript to process events. You register event listeners for events either in the MXML
declaration for the component or in ActionScript. For additional examples of the event
handling, see “Initializing components at run time” on page 138.
The following example registers an event listener in MXML that is processed when you
change views in an Accordion container.
<?xml version="1.0"?>
<!-- components\CompIntroEvent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
width="300"
height="280">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
private function handleAccChange():void {
Alert.show("You just changed views");
}
]]>
</mx:Script>
<!-- The Accordion control dispatches a change event when the
selected child container changes. -->
<mx:Accordion id="myAcc"
height="60"
width="200"
change="handleAccChange();">
<mx:HBox label="Box 1">
<mx:Label text="Put Some Stuff Here"/>
</mx:HBox>
<mx:HBox label="Box 2">
<mx:Label text="Put Different Stuff Here"/>
</mx:HBox>
</mx:Accordion>
</mx:Application>
146 Using Flex Visual Components
This example produces the following image:
You can pass an event object, which contains information about the event, from the
component to the event listener.
Handling events 147
For the Accordion container, the event object passed to the event listener for the change event
is of class IndexChangedEvent. You can write your event listener to access the event object, as
the following example shows:
<?xml version="1.0"?>
<!-- components\CompIntroEventAcc.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
width="300"
height="280">
<mx:Script>
<![CDATA[
// Import the class that defines the event object.
import mx.events.IndexChangedEvent;
import mx.controls.Alert;
private function handleChange(event:IndexChangedEvent):void {
var currentIndex:int=event.newIndex;
Alert.show("You just changed views \nThe new index is "
+ event.newIndex);
}
]]>
</mx:Script>
<!-- The Accordion control dispatches a change event when the
selected child container changes. -->
<mx:Accordion id="myAcc"
height="60"
width="200"
change="handleChange(event);">
<mx:HBox label="Box 1">
<mx:Label text="Put Some Stuff Here"/>
</mx:HBox>
<mx:HBox label="Box 2">
<mx:Label text="Put Different Stuff Here"/>
</mx:HBox>
</mx:Accordion>
</mx:Application>
In this example, you access the newIndex property of the IndexChangedEvent object to
determine the index of the new child of the Accordion container. For more information on
events, see Chapter 5, “Using Events,” on page 83.
148 Using Flex Visual Components
About the component instantiation life cycle
The component instantiation life cycle describes the sequence of steps that occur when you
create a component object from a component class. As part of that life cycle, Flex
automatically calls component methods, dispatches events, and makes the component visible.
The following example creates a Button control and adds it to a container:
<?xml version="1.0"?>
<!-- components\AddButtonToContainer.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Box id="box1" width="200">
<mx:Button id="button1" label="Submit"/>
</mx:Box>
</mx:Application>
The following ActionScript is equivalent to the portion of the MXML code. Flex executes the
same sequence of steps in both examples.
// Create a Box container.
var box1:Box = new Box();
// Configure the Box container.
box1.width=200;
// Create a Button control.
var button1:Button = new Button()
// Configure the Button control.
button1.label = "Submit";
// Add the Button control to the Box container.
box1.addChild(button1);
The following steps show what occurs when you execute the ActionScript code to create the
Button control, and add it to the Box container. When you create the component in MXML,
Flex 2 SDK generates equivalent code.
1. You call the component’s constructor, as the following code shows:
// Create a Button control.
var button1:Button = new Button()
2. You configure the component by setting its properties, as the following code shows:
// Configure the button control.
button1.label = "Submit";
3. You call the addChild() method to add the component to its parent, as the following code
shows:
// Add the Button control to the Box container.
box1.addChild(button1);
Handling events 149
Flex performs the following actions to process this line:
a. Flex sets the parent property for the component to reference its parent container.
b. Flex computes the style settings for the component.
c. Flex dispatches the add event from the button
d. Flex dispatches the childAdd event from the parent container.
e. Flex dispatches the preinitialize event on the component. The component is in a
very raw state when this event is dispatched. Many components, such as the Button
control, create internal child components to implement functionality; for example, the
Button control creates an internal UITextField component to represent its label text.
When Flex dispatches the preinitialize event, the children, including the internal
children, of a component have not yet been created.
f. Flex creates and initializes the component’s children, including the component’s
internal children.
g. Flex dispatches the initialize event on the component. At this time, all of the
component’s children have been initialized, but the component has not been fully
processed. In particular, it has not been sized for layout.
4. Later, to display the application, a render event gets triggered, and Flex does the following.
a. Flex completes all processing required to display the component, including laying out
the component.
b. Flex makes the component visible by setting the visible property to true.
c. Flex dispatches the creationComplete event on the component. The component has
been sized and processed for layout and all properties are set. This event is dispatched
only once when the component is created.
d. Flex dispatches the updateComplete event on the component. Flex dispatches
additional updateComplete events whenever the position, size, or other visual
characteristic of the component changes and the component has been updated for
display.
You can later remove a component from a container using the removeChild() method. The
removed child’s parent property is set to null. If you add the removed child to another
container, it retains its last known state. If there are no references to the component, it is
eventually deleted from memory by the garbage collection mechanism of Adobe Flash Player.
Given this sequence of actions, you should use the events as follows:
■ The preinitialize event occurs too early in the component life cycle for most
initialization activities. It is useful, however, in the rare situations where you must set the
properties on a parent before the children are created.
150 Using Flex Visual Components
■ To configure a component before Flex has determined its visual appearance, use the
initialize event. For example, use this for setting properties that affect its appearance,
height, or width.
■ Use the creationComplete event for actions that rely on accurate values for the
component’s size or position when the component is created. If you use this event to
perform an action that changes the visual appearance of the component, Flex must
recalculate its layout, which adds unnecessary processing overhead to your application.
■ Use the updateComplete event for actions that must be performed each time a
component’s characteristics change, not just when the component is created.
Using styles
Flex defines styles for setting some of the characteristics of components, such as fonts,
padding, and alignment. These are the same styles as those defined and used with Cascading
Style Sheets (CSS). Each visual component inherits many of the styles of its superclasses, and
can define its own styles. Some styles in a superclass might not be used in a subclass. To
determine the styles that a visual component supports, see the styles section of the page for the
component in Adobe Flex 2 Language Reference.
You can set all styles in MXML as tag attributes. Therefore, you can set the padding between
the border of a Box container and its contents by using the paddingTop and paddingBottom
properties, as the following example shows:
<?xml version="1.0"?>
<!-- components\MXMLStyles.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:VBox id="myVBox1" borderStyle="solid">
<mx:Button label="Submit"/>
</mx:VBox>
<mx:VBox id="myVBox2"
borderStyle="solid"
paddingTop="12"
paddingBottom="12" >
<mx:Button label="Submit"/>
</mx:VBox>
</mx:Application>
Using styles 151
You can also configure styles in ActionScript by using the setStyle() method, or in MXML
by using the <mx:Style> tag. The setStyle() method takes two arguments: the style name
and the value. The following example is functionally identical to the previous example:
<?xml version="1.0"?>
<!-- components\ASStyles.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
private function initVBox():void {
myVBox2.setStyle("paddingTop", 12);
myVBox2.setStyle("paddingBottom", 12);
}
]]>
</mx:Script>
<mx:VBox id="myVBox1" borderStyle="solid">
<mx:Button label="Submit"/>
</mx:VBox>
<mx:VBox id="myVBox2"
borderStyle="solid"
initialize="initVBox();">
<mx:Button label="Submit"/>
</mx:VBox>
</mx:Application>
When you use the <mx:Style> tag, you set the styles using CSS syntax or a reference to an
external file that contains style declarations, as the following example shows:
<?xml version="1.0"?>
<!-- components\TagStyles.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Style>
.myStyle {paddingTop: 12; paddingBottom: 12;}
</mx:Style>
<mx:VBox id="myVBox1" borderStyle="solid">
<mx:Button label="Submit"/>
</mx:VBox>
<mx:VBox id="myVBox2"
styleName="myStyle"
borderStyle="solid">
<mx:Button label="Submit"/>
</mx:VBox>
</mx:Application>
152 Using Flex Visual Components
A class selector in a style definition, defined as a label preceded by a period, defines a new
named style, such as myClass in the preceding example. After you define it, you can apply the
style to any component by using the styleName property. In the preceding example, you
apply the style to the second VBox container.
A type selector applies a style to all instances of a particular component type.
The following example defines the top and bottom margins for all Box containers:
<?xml version="1.0"?>
<!-- components\TypeSelStyles.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Style>
Box {paddingTop: 12; paddingBottom: 12;}
</mx:Style>
<mx:VBox id="myVBox" borderStyle="solid">
<mx:Button label="Submit"/>
</mx:VBox>
<mx:Box id="myBox" borderStyle="solid">
<mx:Button label="Submit"/>
</mx:Box>
</mx:Application>
In Flex, some, but not all, styles are inherited from parent containers to their children and
across style types and classes. Because the borderStyle style is not inherited by the VBox
container, this example yields results that are identical to the previous examples. All of these
examples result in the following application:
For more information on styles, see Chapter 18, “Using Styles and Themes,” on page 697.
Using behaviors
A behavior is a combination of a trigger paired with an effect. A trigger is an action similar to
an event, such as a mouse click on a component, a component getting focus, or a component
becoming visible. An effect is a visible or audible change to the component that occurs over a
period of time, measured in milliseconds. Examples of effects are fading, resizing, or moving a
component. You can define multiple effects for a single trigger.
Using behaviors 153
Flex trigger properties are implemented as CSS styles. In Adobe Flex 2 Language Reference,
Triggers are listed under the heading “Effects.” Flex effects are classes, such as the
mx.effects.Fade class.
Behaviors let you add animation, motion, and sound to your application in response to some
user or programmatic action. For example, you can use behaviors to cause a dialog box to
bounce slightly when it receives focus, or to play a sound when the user enters an invalid
value.
Because effect triggers are implemented as CSS styles, you can set the trigger properties as tag
attributes in MXML, in <mx:Style> tags, or in ActionScript by using the setStyle function.
To create the behavior, you define a specific effect with a unique ID and bind it to the trigger.
For example, the following code creates a fade effect named myFade and uses an MXML
attribute to bind the effect to the creationCompleteEffect trigger of an Image control:
<?xml version="1.0"?>
<!-- components\CompIntroBehaviors.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
width="110"
height="100"
backgroundImage="">
<mx:Fade id="myFade" duration="5000"/>
<mx:Image
creationCompleteEffect="{myFade}"
source="@Embed(source='assets/flexlogo.jpg')"/>
</mx:Application>
In this example, the Image control fades in over 5000 milliseconds. The following images
show the fade in over the course of time:
For detailed information on using behaviors, see Chapter 17, “Using Behaviors,” on page 649.
154 Using Flex Visual Components
Applying skins
Skins are graphical style elements that a component uses to control its appearance. Flex
components can have of one or more skins. For example, the Button component has eight
skins, each for a different button state, such as up, down, disabled, selected, and down, and so
on. A control can also have different skins for different subcomponents, for example, the
scroll bar has several skins each for the down arrow, up arrow, and thumb.
For more information on skinning, see Chapter 20, “Using Skins,” on page 805.
Changing the appearance of a
component at run time
You can modify the look, size, or position of a component at run time by using several
component properties, styles, or ActionScript methods, including the following:
■ x and y
■ width and height
■ styles, by using setStyle(stylename, value)
You can set the x and y properties of a component only when the component is in a container
that uses absolute positioning; that is, in a Canvas container, or in an Application or Panel
container that has the layout property set to absolute. All other containers perform
automatic layout to set the x and y properties of their children using layout rules.
Changing the appearance of a component at run time 155
For example, you could use the x and y properties to reposition a Button control 15 pixels to
the right and 15 pixels down in response to a Button control click, as the following example
shows:
<?xml version="1.0"?>
<!-- components\ButtonMove.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
width="150"
height="120"
layout="absolute">
<mx:Script>
<![CDATA[
public function moveButton():void {
myButton.x += 15;
myButton.y += 15;
}
]]>
</mx:Script>
<mx:Button id="myButton"
x="15"
y="15"
label="Move"
click="moveButton();"/>
</mx:Application>
The following example shows the initial image and the results after the user clicks the button
each of two times:
In this application, you can move the Button control without concern for other components.
However, moving a component in an application that contains multiple components, or
modifying one child of a container that contains multiple children, can cause one component
to overlap another, or in some other way affect the layout of the application. Therefore, you
should be careful when you perform run-time modifications to container layout.
156 Using Flex Visual Components
You can set the width and height properties for a component in any type of container. The
following example increases the width and height of a Button control by 15 pixels each time
the user selects it:
<?xml version="1.0"?>
<!-- components\ButtonSize.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
width="150"
height="150">
<mx:Script>
<![CDATA[
public function resizeButton():void {
myButton.height = myButton.height + 15;
myButton.width = myButton.width + 15;
}
]]>
</mx:Script>
<mx:VBox
borderStyle="solid"
height="80"
width="100" >
<mx:Button id="myButton"
label="Resize"
click="resizeButton();"/>
</mx:VBox>
</mx:Application>
This example results in the following progression when the user clicks the button:
If the container that holds the Button does not use absolute positioning, it repositions its
children based on the new size of the Button control. The Canvas container and Panel and
Application containers with layout="absolute" perform no automatic layout, so changing
the size of one of their children does not change the position or size of any of the other
children.
The stored values of width and height are always in pixels regardless of whether the
N OT E
values were originally set as fixed values, as percentages, or not set at all.
Changing the appearance of a component at run time 157
Extending components
Flex 2 SDK provides several ways for you to extend existing components or to create
components. By extending a component, you can add new properties or methods to it.
For example, the following MXML component, defined in the file MyComboBox.mxml,
extends the standard ComboBox control to initialize it with the postal abbreviations of the
states in New England:
<?xml version="1.0"?>
<!-- components\myComponents\MyComboBox.mxml -->
<mx:ComboBox xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:dataProvider>
<mx:String>CT</mx:String>
<mx:String>MA</mx:String>
<mx:String>ME</mx:String>
<mx:String>NH</mx:String>
<mx:String>RI</mx:String>
<mx:String>VT</mx:String>
</mx:dataProvider>
</mx:ComboBox>
This example also shows how the MXML compiler lets you use some coding shortcuts. Flex
expects the dataProvider to be an array, so you do not have to specify a <mx:Array> tag.
After you create it, you can use your new component anywhere in your application by
specifying its filename as its MXML tag name, as the following example shows:
<?xml version="1.0"?>
<!-- components\MainMyComboBox.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:MyComps="myComponents.*"
width="150"
height="150">
<MyComps:MyComboBox id="stateNames"/>
</mx:Application>
In this example, the new component is in the same directory as your application file, and
maps the local namespace, indicated by the asterisk (*), to the MyComps identifier.
Flex lets you create custom components using either of the following methods. The method
you choose depends on your application and the requirements of your component.
■ Create components as MXML files and use them as custom tags in other MXML files.
MXML components provide an easy way to extend an existing component, particularly to
modify the behavior of an existing component or add a basic feature to an existing
component.
158 Using Flex Visual Components
■ Create components as ActionScript files by subclassing the UIComponent class or any of
its subclasses, and use the resulting classes as custom tags. ActionScript components
provide a powerful tool for creating new visual or nonvisual components.
For detailed information on creating custom components, see Creating and Extending Flex 2
Components.
Extending components 159
160 Using Flex Visual Components
CHAPTER 7
Using Data Providers
and Collections
7
Several Adobe Flex controls take input from a data provider such as an array or XML object. A
Tree control, for example, reads data from a data provider to define the structure of the tree
and any associated data assigned to each tree node. Flex controls use collection classes to
represent data providers. A collection contains a group of objects, and provides a set of
methods that let you access, sort, filter, and modify the items in the collection.
This topic describes data providers and the collection classes. It provides an introduction to
using data providers in controls and discusses how to use the collection classes to access and
manipulate data. Several topics, including Chapter 12, “Using Data-Driven Controls,” on
page 439 and Chapter 11, “Using Menu-Based Controls,” on page 407 describe Flex controls
that use data providers.
Contents
About data providers and collections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .161
Using IList interface methods and properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
Using ICollectionView interface methods and properties . . . . . . . . . . . . . . . . . . . . . 176
</mx:Application> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
Using hierarchical data providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Using remote data providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
About data providers and collections
Many controls and containers require data for display, for user interaction, or to structure a
control such as a menu. To provide this data, you must understand the concepts of data
providers and collections and how collections work.
161
About data providers
Several Flex framework components, including all List based controls, represent data from a
data provider, an object that contains data required by the control. For example, a Tree
control’s data provider determines the structure of the tree and any associated data assigned to
each tree node, and a ComboBox control’s data provider determines the items in the control’s
drop-down list. Many standard controls, including the ColorPicker and MenuBar controls
also get data from a data provider. Controls that display application data are sometimes
referred to as data provider controls.
The following components use data providers:
■ Repeater component
■ Chart controls, such as the LineChart control
■ ColorPicker control
■ ComboBox control
■ DataGrid control
■ DateField control
■ HorizontalList control
■ List control
■ Menu control
■ MenuBar control
■ PopUpMenuButton control
■ TileList control
■ Tree control
■ ButtonBar control
■ LinkBar control
■ TabBar control
■ ToggleButtonBar control
162 Using Data Providers and Collections
The simplest data provider can be an array of strings or objects; for example, you can use the
following code to define a static ComboBox control:
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
[Bindable]
public var myArray:Array = ["AL", "AK", "AR"];
]]>
</mx:Script>
<mx:ComboBox id="myCB0" dataProvider="{myArray}"/>
</mx:Application>
However, using a raw data object, such as an Array or Object, as a data provider has
limitations:
■ Raw objects are often not sufficient if you have data that changes, because the control does
not receive a notification of any changes to the base object. The control, therefore, does
not get updated until it must be redrawn due to other changes in the application or if the
data provider is reassigned; at this time, it gets the data again from the updated Array. In
the preceding example, if you programmatically add states to the Array, they do not show
up in the ComboBox control unless you reassign the control’s dataProvider property.
■ Raw objects do not provide advanced tools for accessing, sorting, or filtering data. For
example, if you use an Array as the data provider, you must use the native Adobe Flash
Array methods to manipulate the data.
Flex provides a collection mechanism to ensure data synchronization and provide both simpler
and more sophisticated data access and manipulation tools. Collections can also provide a
consistent interface for accessing and managing data of different types. For more information
on collections, see “About collections” on page 167.
For detailed descriptions of the individual controls, see the pages for the controls in Adobe
Flex 2 Language Reference. For information on programming with many of the data provider-
based controls, see Chapter 12, “Using Data-Driven Controls,” on page 439.
Data provider types
The Flex framework supports two basic types of data provider:
Linear or list-based data providers are flat data consisting of some number of objects, each
of which has the same structure; they are often one-dimensional Arrays, or objects derived
from such Arrays, such as ActionScript object graphs. (You can also use an
XMLListCollection object as a linear data provider.)
About data providers and collections 163
You can use list-based data providers with all data provider controls, and typically use them
for all such controls except Tree and most menu-based control instances. If the data provider
contents can change dynamically, you typically use the ArrayCollection class and either the
IList or ICollectionView interface methods and properties to represent and manipulate these
data providers.
Hierarchical data providers consist of cascading levels of often asymmetrical data. Often, the
source of the data is an XML object, but the source can be a generic Object or concrete class.
You typically use a hierarchical data providers with Flex controls that are designed to display
hierarchical data:
■ Tree
■ Menu, MenuBar, and PopUpMenuButton.
You can also extract data from hierarchical data provider to use in controls such as List or
DataGrid that take linear data.
A hierarchical data provider defines a data structure that matches the layout of a tree or
cascading menu. For example, a tree often has a root node, with one or more branch or leaf
child nodes. Each branch node can hold additional child branch or leaf nodes, but a leaf node
is an endpoint of the tree.
The Flex hierarchical data controls use data descriptor interfaces to access and manipulate
hierarchical data providers, and the Flex framework provides one class, the
DefaultDataDescriptor class that implements the required interfaces. If your data provider
does not conform to structure required by the default data descriptor, you can create your own
data descriptor class that implements the required interfaces.
You can use an ArrayCollection class, XMLListCollection class, ICollectionView interface or
IList interface to access and manipulate dynamic hierarchical data.
For more information on using hierarchical data providers, see “Using hierarchical data
providers” on page 197.
164 Using Data Providers and Collections
Data providers and the uid property
Flex data-driven controls, including all controls that are subclasses of List class, use a unique
identifier (uid) to track data provider items. Flex can automatically create and manage uids.
However, there are circumstances when you must supply your own uid property by
implementing the IUID interface, or when supplying your own uid property improves
processing efficiency.
When Flex creates a UID for an object, such as an item in an ArrayCollection, it adds the
NO T E
UID as an mx_internal_uid property of the item. Flex creates mx_internal_uid properties
for any objects that are dynamic and do not have bindable properties. To avoid having
Flex create mx_internal_uid properties, the object class should do any of the following
things: have at least one property with a [Bindable] metadata tag, implement the IUID
interface, or have a uid property with a value.
If Flex must consider two or more different objects to be identical you must implement the
IUID interface so that you can assign the same uid to multiple objects. A typical case where
you must implement the IUID interface is an application that uses windowed paged
collections. As the cursor moves through the collection, a particular item might be pulled
down from the server and released from memory repeatedly. Every time the item is pulled into
memory a new object is created to represent the item. If you need to compare items for
equality, Flex should consider all objects that represent the same item to be the same “thing.”
More common than the case where you must implement the IUID interface is the case where
you can improve processing efficiency by doing so. As a general rule, you do not implement
the IUID interface if the data provider elements are members of dynamic classes. Flex can
automatically create a uid property for these classes. There is still some inefficiency however,
so you might consider implementing the IUID interface if processing efficiency is particularly
important.
In all other cases, Flex uses the Dictionary mechanism to manage the uid, which might not be
as efficient as supplying your own UID.
Because the Object and Array classes are dynamic, you normally do not do anything special
for data providers whose items belong to these classes. However, you should consider
implementing the IUID if your data provider members belong to custom classes that you
define.
About data providers and collections 165
The IUID interface contains a single property, uid, which is a unique identifier for the class
member, and no methods. Flex provides a UIDUtil class that uses a pseudo-random number
generator to create an identifier that conforms to the standard GUID format. Although this
identifier is not guaranteed to be universally unique, it should be unique among all members
of your class. To implement a class that uses the UIDUtil class, such as a Person class that has
fields for a first name, last name, and id, you can use the following pattern:
package {
import mx.core.IUID;
import mx.utils.UIDUtil;
[Bindable]
public class Person implements IUID {
public var id:String;
public var firstName:String;
public var lastName:String;
private var _uid:String;
public function Person() {
_uid = createUID();
}
public function get uid():String {
return _uid;
}
public function set uid(value:String):void {
// Do nothing, the constructor created the uid.
}
}
}
You do not need to use the UIDUtil class in a case where the objects contain a uniquely-
identifying field such as an employee ID. In this case, you can use the person’s ID as the uid
property, because the uid property values have uniquely identify the object only in the data
provider. The following example implements this approach.
package
{
import mx.core.IUID;
[Bindable]
public class Person implements IUID {
public var employee_id:String;
public var firstName:String;
public var lastName:String;
public function get uid(): String {
return employee_id;
166 Using Data Providers and Collections
}
public function set uid(value: String): void {
employee_id=value;
}
}
}
Object cloning does not manage or have a relationship with UIDs, so if you clone
NO TE
something that has an internal UID you must also change that internal UID. UIDs are
stored on mx_internal_uid only for dynamic Objects. Instances of data classes that
implement IUID will store their UIDs in a .uid property so that is the property that must be
changed after cloning.
However, dataproviders do not need to implement IUID. If they are instances of data
classes that do not implement IUID and are not dynamic objects, the clone technique
should work correctly, but most dataprovider items should implement IUID, especially if
cloning those objects is not required.
About collections
A collection provides a uniform method to access and represent a data provider’s data. The
collection creates a level of abstraction between Flex components and the data that you use to
populate them. The collection interfaces and implementations provide the following features:
■ They ensure that a control is properly updated when the underlying data changes.
Controls do not update when non-collection data providers change. (They do update to
reflect the new data the next time they are refreshed.) If the data provider is a collection,
the controls update immediately after the collection change occurs.
■ They provide mechanisms for handling paged data coming from remote data providers
that may not initially be available and may arrive over a period of time.
■ They provide a consistent set of operations on the data, independent of those provided by
the raw data provider objects. For example, you could create a custom class that
implements the IList interface and lets you insert and delete objects by using an index into
the collection, independent of whether the underlying data is, for example, in an array or
an object.
■ Collections that conform to the ICollectionView interface provide a specific view of the
data that can be in sorted order, or filtered by a developer-supplied method. These
limitations affect only the collection’s view, and do not change the underlying data.
■ You can use a single collection to populate multiple components from the same data
provider.
About data providers and collections 167
■ You can use collections to switch data providers for a component at run time, and to
modify a data provider so that changes are reflected by all components that use the data
provider.
■ You can use collection methods to access data in the underlying data object.
If you use a raw object, such as an Array, as a control’s data provider, Flex automatically
NO T E
wraps the object in a collection wrapper. The control does not automatically detect
changes that are made directly to the raw object. A change in the length of an array, for
example, does not result in an update of the control. You can, however, use an object
proxy, a listener interface, or the itemUpdated property to notify the view of certain
changes.
Collection interfaces
The Flex framework collection model uses these interfaces to define how a collection
represents data and provides access to it:
Interface Description
IList A direct representation of items organized in an ordinal fashion. The
interface presents the data from the data provider in the same order as it
exists in the provider, and provides access and manipulation methods
based on an index. The IList class does not provide sorting, filtering, or
cursor functionality.
ICollectionView A view of a collection of items. You can modify the view to show the data
in sorted order and to show a subset of the items in the data provider, as
specified by a filter function. A class that implements this interface can
use an IList interface as the underlying collection.
The interface provides access to an IViewCursor object for access to the
items.
IViewCursor Enumerates an ICollectionView object bidirectionally. The view cursor
provides find, seek, and bookmarking capabilities, and lets you modify
the underlying data (and the view) by inserting and removing items.
The IList and ICollectionView interfaces provide two alternate methods for accessing and
changing data. The IList interface is simpler; it provides add, set, get, and remove operations
that operate directly on linear data.
The ICollectionView interface (also called the collection view) provides a more complex set of
operations than the IList interface, and is appropriate when the underlying data may not be
organized linearly. Its data access techniques, however, are more complex than those of the
IList interface, so you should use the IList interface if you need only simple, indexed access to
a linear collection. The collection view can represent a subset of the underlying data, as
determined by a sort or filter operation.
168 Using Data Providers and Collections
The standard Flex collection classes, ArrayCollection and XMLListCollection, implement
both the collection view (ICollectionView) interface and the IList interface.
For information on using the IList interface methods and property, see “Using IList interface
methods and properties” on page 174. For information on using the ICollectionView
interface methods and properties, Including the IViewCursor object that the interface
exposes, see “Using ICollectionView interface methods and properties” on page 176.
Collection classes
The following table describes the public classes in the mx.collections package. It does not
include constant classes, event and error classes. For complete reference information on
collection-related classes, see the collections and collections.errors packages, and the
CollectionEvent and CollectionEventKind classes in Adobe Flex 2 Language Reference.
Class Description
ArrayCollection Implements the IList and ICollectionView interfaces for use with array-
based data providers.
XMLListCollection Implements the IList and ICollectionView interfaces, and a subset of
XMLList methods for use with XML-based data providers.
CursorBookmark Represents the position of an IViewCursor instance within an
ICollectionView instance. You can save a view cursor position in a
CursorBookmark object and use the object to return the view cursor to
the position at a later time.
Sort Provides the information and methods required to sort an
ICollectionView instance.
SortField Provides properties and methods that determine how a specific field
affects how data is sorted in an ICollectionView instance.
ItemResponder (Used only if the data source is remote.) Handles cases when requested
data is not yet available.
ListCollectionView Adapts an object that implements the IList interface to the
ICollectionView interface so that it can be passed to anything that
expects an IList or an ICollectionView. This class is the superclass of the
ArrayCollection and XMLListCollection classes
About data providers and collections 169
Specifying data providers in MXML applications
The Flex framework lets you specify and access data providers in many ways. For example, as
with any MXML control, you can define the data provider by using an <mx:dataProvider>
property child tag of a control, or you can define the data provider in an ActionScript
assignment. All access techniques belong to one of three major patterns:
■ Using a raw data object, such as an Array.
■ Using a collection class object directly. This pattern is particularly useful for local
collections where object reusability is less important.
■ Using an interface. This pattern provides the maximum of independence from the
underlying implementation.
Using a raw data object as a data provider
You can use a raw data object, such as an Array object, directly as a data provider any time the
data is static. For example, you could use an array for a static list of U.S. Postal Office state
designators. Do not use the data object directly as the dataProvider property of a control if the
object contents can change dynamically, for example in response to user input or
programmatic processing.
The result returned by an HTTPService or WebService often is an Array, and if you treat that
data as read-only, you can use the Array directly as a data provider. (RemoteObject classes
often return ArrayCollections.)
List-based controls, however, internally turn Array-based data providers into collections, so
there is no performance advantage of using an Array as the data provider. If you pass an Array
to multiple controls, it is more efficient to convert the Array into a collection when the data is
received, and then pass the collection to the controls.
To use a raw data object, assign the object to the control’s dataProvider control, or define
the object directly in the body of the control MXML tag, as shown in the example in “About
data providers” on page 162.
Using a collection object directly
You can use an object that implements the ICollectionView or IList interface as a data
provider directly in an MXML control by assigning it to the component’s dataProvider
property. This technique is more direct than using an interface and is appropriate if the data
provider always belongs to a specific collection class.
170 Using Data Providers and Collections
For list-based controls, you often use an ArrayCollection object as the data provider, and
populate the ArrayCollection using an Array. The following example shows a data provider
that specifies the data for a ComboBox control:
<?xml version="1.0"?>
<!-- dpcontrols\ArrayCollectionInComboBox.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:ComboBox id="myCB">
<mx:ArrayCollection id="stateArray">
<mx:Object label="AL" data="Montgomery"/>
<mx:Object label="AK" data="Juneau"/>
<mx:Object label="AR" data="Little Rock"/>
</mx:ArrayCollection>
</mx:ComboBox>
</mx:Application>
In this example, the dataProvider default property of the ComboBox defines an
ArrayCollection object whose source default property is an array of Objects, each of which
has a label and data field. (The ArrayCollection source property’s takes an Array object, so
there is no need to use an <mx:Array> tag in this example.)
The following example uses ActionScript to declare and create the ArrayCollection object:
<?xml version="1.0"?>
<!-- dpcontrols\ArrayCollectionInAS.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="initData()">
<mx:Script>
<![CDATA[
import mx.collections.*;
[Bindable]
public var stateArray:ArrayCollection;
public function initData():void {
stateArray=new ArrayCollection(
[{label:"AL", data:"Montgomery"},
{label:"AK", data:"Juneau"},
{label:"AR", data:"Little Rock"}]);
}
]]>
</mx:Script>
<mx:ComboBox id="myComboBox" dataProvider="{stateArray}"/>
</mx:Application>
About data providers and collections 171
After you define the ComboBox control, the dataProvider property of the ComboBox
control provides access to the collection that represents the underlying data provider source
object, and you can use the property to modify the data provider. If you add the following
button to the preceding code, for example, you can click the button to add the label and data
for Arizona to the end of the list in the ComboBox.
<mx:Button label="Add AZ"
click="myComboBox.dataProvider.addItem({'label':'AZ',
'data':'Phoenix'});"/>
It is generally a better practice, and highly recommended, to reference the collection directly,
as in the following example:
<mx:Button label="Add AZ"
click="stateArray.addItem({'label':'AZ', 'data':'Phoenix'});"/>
Accessing the data provider using collection interfaces
If you know that a control’s data provider can always be represented by a specific collection
class, use the class directly, as shown in “Using a collection object directly”. If your code might
be used with different underlying collection types, then you should use the ICollectionView
Interface in your application code, as shown in the following meta-example:
public var myICV:ICollectionView = indeterminateCollection;
<mx:ComboBox id="cb1" dataProvider="{myICV}" initialize="sortICV()"/>
You can then manipulate the interface as needed to select data for viewing, or to get and
modify the data in the underlying data source. For more detailed information the techniques
provided by the collection interfaces, see Using IList interface methods and properties
on page 174 and Using ICollectionView interface methods and properties on page 176.
Example: Using a simple data provider
The following sample code shows how you can use basic collection classes to represent and
manipulate an Array for use in a control. This example shows the following features:
■ Using an ArrayCollection to represent data in an array
■ Sorting the ArrayCollection
■ Inserting data in the ArrayCollection.
172 Using Data Providers and Collections
This example also shows the insertion’s effect on the Array and the ArrayCollection
representation of the Array:
<?xml version="1.0"?>
<!-- dpcontrols\SimpleDP.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="600"
initialize="sortAC()">
<mx:Script>
<![CDATA[
import mx.collections.*;
// Function to sort the ArrayCollection in descending order.
public function sortAC():void {
var sortA:Sort = new Sort();
sortA.fields=[new SortField("label")];
myAC.sort=sortA;
//Refresh the collection view to show the sort.
myAC.refresh();
}
// Function to add an item in the ArrayCollection.
// Data added to the view is also added to the underlying Array.
// The ArrayCollection must be sorted for this to work.
public function addItemToMyAC():void {
myAC.addItem({label:"MD", data:"Annapolis"});
}
]]>
</mx:Script>
<!-- An ArrayCollection with an array of objects -->
<mx:ArrayCollection id="myAC">
<!-- Use an mx:Array tag to associate an id with the array. -->
<mx:Array id="myArray">
<mx:Object label="MI" data="Lansing"/>
<mx:Object label="MO" data="Jefferson City"/>
<mx:Object label="MA" data="Boston"/>
<mx:Object label="MT" data="Helena"/>
<mx:Object label="ME" data="Augusta"/>
<mx:Object label="MS" data="Jackson"/>
<mx:Object label="MN" data="Saint Paul"/>
</mx:Array>
</mx:ArrayCollection>
<mx:HBox width="100%">
<!-- A ComboBox populated by the underlying Array object.
This control shows that Array retains its original order
and MD is inserted at the end of the Array. -->
<mx:ComboBox id="cb2" rowCount="10" dataProvider="{myArray}"/>
<!-- A ComboBox populated by the collection view of the Array. -->
<mx:ComboBox id="cb1" rowCount="10" dataProvider="{myAC}"/>
<mx:Button id="b1" label="Add MD" click="addItemToMyAC();"/>
About data providers and collections 173
</mx:HBox>
</mx:Application>
Using IList interface methods and
properties
The IList interface provides simple methods for indexed access to linear data. The interface
provides a direct representation of the underlying data provider. Thus, any operation that
changes the collection changes the data provider in a similar manner: if you insert a item as
the third item in the collection, it also is the third item in the underlying data source.
If you use the ICollectionView interface to sort or filter a collection, do not use the IList
NO T E
interface to manipulate the data, as the results are indeterminate.
The interface includes properties and methods that let you do the following:
■ Get, set, add, or remove an item at a specific index into the collection.
■ Add an item at the end of the collection.
■ Get the index of a specific item in the collection.
■ Remove all items in the collection.
■ Get the length of the collection.
You can use the IList interface methods and properties directly on any of the following classes
or properties:
■ ArrayCollection class
■ XMLList class
■ dataProvider property of standard Flex controls.
The following sample code uses an ArrayCollection object and its implementation of the IList
interface methods to display an array of elements in a ComboBox control. For an example
that uses IList interface methods to manage an ArrayCollection of objects with multiple fields,
see “Example: Modifying data in DataGrid control” on page 194.
In the following example the Array data source initially consists of the following elements:
"AZ", "MA", "MZ", "MN", "MO", "MS"
174 Using Data Providers and Collections
When you click the Button control, the application uses the length property and several
methods of the IList interface to do the following:
■ Change the data in the array and the displayed data in the ComboBox control to a correct
alphabetical list of the U.S. ZIP codes for states that start with M:
MA, ME, MI, MN, MO, MS, MT
■ Display in a TextArea control information about the tasks it performed and the resulting
array.
The code includes comments that describe the changes to the data provider.
<?xml version="1.0"?>
<!-- dpcontrols\UseIList.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="initData()">
<mx:Script>
<![CDATA[
import mx.collections.*;
// The data provider is an Array of Strings
public var myArray:Array = ["AZ", "MA", "MZ", "MN", "MO", "MS"];
// Declare an ArrayCollection that represents the Array.
[Bindable]
public var myAC:ArrayCollection;
//Initialize the ArrayCollection.
public function initData():void {
myAC = new ArrayCollection(myArray);
}
// The function to change the collection, and therefore
// the Array.
public function changeCollection():void {
// Get the original collection length.
var oldLength:int=myAC.length;
// Remove the invalid first item, AZ.
var removedItem:String=String(myAC.removeItemAt(0));
// Add ME as the second item. (ILists used 0-based indexing.)
myAC.addItemAt("ME", 1);
// Add MT at the end of the Array and collection.
myAC.addItem("MT");
// Change the third item from MZ to MI.
myAC.setItemAt("MI", 2);
// Get the updated collection length.
var newLength:int=myAC.length;
// Get the index of the item with the value ME.
var addedItemIndex:int=myAC.getItemIndex("ME");
Using IList interface methods and properties 175
// Get the fifth item in the collection.
var index4Item:String=String(myAC.getItemAt(4));
// Display the information in the TextArea control.
ta1.text="Start Length: " + oldLength + ". New Length: " +
newLength;
ta1.text+=".\nRemoved " + removedItem;
ta1.text+=".\nAdded ME at index " + addedItemIndex;
ta1.text+=".\nThe item at index 4 is " + index4Item + ".";
// Show that the base Array has been changed.
ta1.text+="\nThe base Array is: " + myArray.join();
}
]]>
</mx:Script>
<mx:ComboBox id="myCB" rowCount="7" dataProvider="{myAC}"/>
<mx:TextArea id="ta1" height="75" width="300"/>
<mx:Button label="rearrange list" click="changeCollection();"/>
</mx:Application>
Using ICollectionView interface methods
and properties
The ICollectionView interface represents a view of the underlying data source as a collection
of items. It has the following major features:
■ You can modify the view to show the data in sorted order or to show a subset of the items
in the data provider without changing the underlying data. For more information, see
“Sorting and filtering data for viewing” on page 177
■ You can access the collection data using a cursor, which lets you move through the
collection, use bookmarks to save specific locations in the collection, and insert and delete
items in the collection (and therefore in the underlying data source). For more
information, see “Using the IViewCursor interface” on page 180
■ You can use ICollectionView objects to represent remote data that might not initially be
available, or where parts of the data set might become available at different times. For
more information, see “Using collection change notifications” on page 191 and “Using
remote data providers” on page 213
You can use the ICollectionView interface methods and properties directly on any of the
following classes or properties:
■ ArrayCollection class
■ XMLListCollection class
176 Using Data Providers and Collections
■ dataProvider property of all standard Flex controls except those that are subclasses of the
NavBar class (ButtonBar, LinkBar, TabBar, ToggleButtonBar)
The following sections describe the basic ICollectionView operations using a list-based
collection, but can also apply to similar operations on a hierarchical collection.
Sorting and filtering data for viewing
The ICollectionView interface lets you sort and filter the data in the data provider so that the
view represented by the collection is a reordered subset of the underlying data. These
operations have no effect on the data provider contents, only on the subset that the collection
view represents, and therefore what any control that uses the collection displays.
Sorting
The Sort class lets you sort data in the collection. You can specify multiple fields to use in
sorting the data, require that the resulting entries be unique, and specify a custom comparison
function to use for ordering the sorted output. You can also use the Sort class to find items in
a collection. When you create a Sort class, or change its properties, you must call the
refresh() method on the collection to show the results.
You use the SortField class to specify the fields to use in the sort. You create the SortField
objects and put them in the Sort class object’s fields array.
The following shows a function to sort a collection. In this example, myAC is a collection
view of an Array of objects containing label and name fields. The primary sort is a descending,
case-insensitive sort on the area field and the secondary sort is an ascending case-sensitive sort
on the label field. You might call it as the initialize event handler for a control that must
display a specific sorted view of a collection.
//Sort the ICollectionView in descending order.
public function sortAC():void {
//Create a Sort object.
var sortA:Sort = new Sort();
// Sort first on the area field, then the label field.
// The second parameter specifies that the sort is case-insensitive.
// A true third parameter specifies a descending sort.
sortA.fields=[new SortField("area", true, true),
new SortField("label")];
myAC.sort=sortA;
//Refresh the collection view to show the sort.
myAC.refresh();
}
Using ICollectionView interface methods and properties 177
Filtering
You use a filter function limit the ICollection view to a subset of the data provider source. The
function must take a single Object parameter, which corresponds to a collection item, and
must return a Boolean value specifying whether to include the item in the collection view. As
with sorting, when you specify or change the filter function, you must call the refresh()
method on the collection to show the filtered results. To limit a collection view of an array of
strings to contain only strings starting with M, for example, use the following filter function:
public function stateFilterFunc(item:Object):Boolean
{
return item >= "M" && item < "N";
}
Example: Sorting and filtering an ArrayCollection
The following example shows the use of the filter function and a sort together. You can use the
buttons to sort, or filter the collection, or you can do both. Use the Reset button to restore the
collection view to its original state.
<?xml version="1.0"?>
<!-- dpcontrols\SortFilterArrayCollection.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="600">
<mx:Script>
<![CDATA[
import mx.collections.*;
// Function to sort the ICollectionView
// in ascending order.
public function sortAC():void {
var sortA:Sort = new Sort();
sortA.fields=[new SortField("label")];
myAC.sort=sortA;
//Refresh the collection view to show the sort.
myAC.refresh();
}
// Function to filter out all items with labels
// that are not in the range of M-N.
public function stateFilterFunc(item:Object):Boolean {
return item.label >= "M" && item.label < "O";
}
// Function to apply the filter function the ICollectionView.
public function filterAC():void {
myAC.filterFunction=stateFilterFunc;
//Refresh the collection view to apply the filter.
myAC.refresh();
}
178 Using Data Providers and Collections
// Function to Reset the view to its original state.
public function resetAC():void {
myAC.filterFunction=null;
myAC.sort=null;
//Refresh the collection view.
myAC.refresh();
}
]]>
</mx:Script>
<!-- An ArrayCollection with an array of objects. -->
<mx:ArrayCollection id="myAC">
<mx:Array id="myArray">
<mx:Object label="LA" data="Baton Rouge"/>
<mx:Object label="NH" data="Concord"/>
<mx:Object label="TX" data="Austin"/>
<mx:Object label="MA" data="Boston"/>
<mx:Object label="AZ" data="Phoenix"/>
<mx:Object label="OR" data="Salem"/>
<mx:Object label="FL" data="Tallahassee"/>
<mx:Object label="MN" data="Saint Paul"/>
<mx:Object label="NY" data="Albany"/>
</mx:Array>
</mx:ArrayCollection>
<!-- Buttons to filter, sort, or reset the view in the second ComboBox
control. -->
<mx:HBox width="100%">
<mx:Button id="sortButton" label="Sort" click="sortAC();"/>
<mx:Button id="filterButton" label="Filter" click="filterAC();"/>
<mx:Button id="resetButton" label="Reset" click="resetAC();"/>
</mx:HBox>
<mx:HBox width="100%">
<!-- A ComboBox populated by the underlying Array object.
This control shows that Array retains its original order. -->
<mx:ComboBox id="cb2" rowCount="10" dataProvider="{myArray}"/>
<!-- A ComboBox populated by the collection view of the Array. -->
<mx:ComboBox id="cb1" rowCount="10" dataProvider="{myAC}"/>
</mx:HBox>
</mx:Application>
For a more complex example of sorting a DataGrid control, which both does an initial sort of
the data and does a custom sort when you click a column heading, see “Example: Sorting a
DataGrid on multiple columns” on page 476.
Using ICollectionView interface methods and properties 179
Using the IViewCursor interface
The ICollectionView interface includes a createCursor() method that returns an
IViewCursor object, also called a cursor, that you can use to traverse the items in the view and
to access and modify data in the collection. A cursor is a position indicator; it points to a
particular item in the collection. You can use IViewCursor methods and properties to perform
the following operations:
■ Move the cursor backward or forward.
■ Move the cursor to specific items.
■ Get the item at a cursor location.
■ Add, remove, and change items.
■ Save a cursor position by using a bookmark, and return to it later.
When you use standard Flex collection classes, ArrayCollection and XMLListCollection, you
use the IViewCursor interface directly, you do not reference an object instance, as shown in
the following code snippet:
public var myAC:ICollectionView = new ArrayCollection(myArray);
public var myCursor:IViewCursor;
.
.
myCursor=myAC.createCursor();
Manipulating the view cursor
The IViewCursor interface includes the following methods and properties for moving the
cursor:
■ The moveNext() and movePrevious() methods move the cursor forward and backward
by one item. Use the beforeFirst and afterLast properties to check whether you’ve
reached the bounds of the view. The following example moves the cursor to the last item
in the view:
while (! myCursor.afterLast) {
myCursor.moveNext();
}
■ The findAny(), findFirst(), and findLast(), methods move the cursor to an item
that matches the parameter. Before you can use these methods, you must apply a Sort to
the ICollectionView implementation (because the functions use Sort methods).
If it is not important to find the first occurrence of an item or last occurrence of an item in
a non-unique index, the findAny() method can be somewhat more efficient than either
the findFirst() or the findLast() method.
180 Using Data Providers and Collections
If the associated collection is remote, and not all of the items are cached locally, the find
methods begin an asynchronous fetch from the remote collection; if a fetch is already in
progress, they wait for it to complete before making another fetch request.
The following example finds an item inside a collection of simple objects, in this case, an
ArrayCollection of state ZIP Code strings. It creates a default Sort object, applies it to an
ArrayCollection object, and finds the first instance of the string "MZ" in a simple array of
strings:
var sortD:Sort = new Sort();
// The null first parameter on the SortField constructor specifies a
// collection of simple objects (String, numeric, or Boolean values).
// The true second parameter specifies a case-insensitive sort.
sortD.fields = [new SortField(null, true)];
myAC.sort=sortD;
myAC.refresh();
myCursor.findFirst("MZ");
To find a complex object, the findFirst() method can search on multiple sort fields.
You cannot, however, skip fields in the parameter of any of the find methods. If an object
has three fields, for example, you can specify any of the following field combinations in
the parameter: 1, 1,2, 1,2,3, but you cannot specify only fields 1 and 3.
Both of the following lines will find an object with the label value "ME" and data value
"Augusta":
myCursor.findFirst({label:"ME"});
myCursor.findFirst({label:"ME", data:"Augusta"});
■ The seek() method moves the cursor to a position relative to a bookmark. You use this
method to move the cursor to the first or last item in a view, or to move to a bookmark
position that you have saved. For more information on using bookmarks and the seek()
method, see “Using bookmarks” on page 183
Getting, adding and removing items
The IViewCursor interface includes the following methods and properties for accessing and
changing data in the view:
■ The current property is a reference to the item at the current cursor location.
■ The insert() method inserts an item before the current cursor location. Note, however,
that if the collection is sorted, (for example, to do a find()) the sort moves the item to
the sorted order location, not the cursor location.
■ The remove() method removes the item at the current cursor location; if the removed
item is not the last item, the cursor then points to the location after the removed item.
Using ICollectionView interface methods and properties 181
The following example shows the results of using the insert() and remove() on the
current property:
<?xml version="1.0"?>
<!-- dpcontrols\GetAddRemoveItems.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="initData();">
<mx:Script>
<![CDATA[
import mx.collections.*;
public var myArray:Array = [{label:"MA", data:"Massachusetts"},
{label:"MN", data:"Minnesota"}, {label:"MO", data:"Missouri"}];
[Bindable]
public var myAC:ArrayCollection;
public var myCursor:IViewCursor;
// Initialize the ArrayCollection when you
// initialize the application.
public function initData():void {
myAC = new ArrayCollection(myArray);
}
// The function to change the collection,
// and therefore the Array.
public function testCollection():void {
// Get an IViewCursor object for accessing the collection
data.
myCursor=myAC.createCursor();
ta1.text="At start. cursor is at: " + myCursor.current.label;
var removedItem:String=String(myCursor.remove());
ta1.text+="\nAfter removing the current item, the cursor is
at: "
+ myCursor.current.label;
myCursor.insert({label:"ME", data:"Augusta"});
ta1.text+="\nAfter adding an item, the cursor is at: "
+ myCursor.current.label;
}
]]>
</mx:Script>
<mx:ComboBox id="myCB" rowCount="7" dataProvider="{myAC}"/>
<mx:TextArea id="ta1" height="75" width="350"/>
<mx:Button label="run test" click="testCollection();"/>
</mx:Application>
182 Using Data Providers and Collections
Using bookmarks
You use a bookmark to save a cursor location for later use. You can also use the built-in FIRST
and LAST bookmark properties to move the cursor to the first or last item in the view.
To create and use a bookmark:
1. Move the cursor to a desired location in the view.
2. Assign the current value of the bookmark property to a variable, as in the following line:
var myBookmark:CursorBookmark=myIViewCursor.bookmark;
3. Do some operations that might move the cursor.
4. When you must return to the bookmarked cursor location (or to a specific offset from the
bookmarked location), call the IViewCursor seek() method, as in the following line:
myIViewCursor.seek(myBookmark);
Using ICollectionView interface methods and properties 183
The following example counts the number of items in a collection between the selected item
in a ComboBox and the end of the collection, and then returns the cursor to the initial
location:
<?xml version="1.0"?>
<!-- dpcontrols\UseBookmarks.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="run();">
<mx:Script>
<![CDATA[
import mx.collections.*;
private var myCursor:IViewCursor;
// Initialize variables.
public function run():void {
// Initialize the cursor.
myCursor=myAC.createCursor();
// The findFirst() method, used in
// countFromSelection() requires a
// sorted view.
var sort:Sort = new Sort();
sort.fields=[new SortField("label")];
myAC.sort=sort;
//You must refresh the view to apply the sort.
myAC.refresh();
}
// Count the items following the current
// cursor location.
public function countLast(theCursor:IViewCursor):int {
var counter:int=0;
// Set a bookmark at the current cursor location.
var mark:CursorBookmark=theCursor.bookmark;
// Move the cursor to the end of the Array.
// The moveNext() method returns false when the cursor
// is after the last item.
while (theCursor.moveNext()) {
counter++;
}
// Return the cursor to the initial location.
theCursor.seek(mark);
return counter;
}
// Function triggered by ComboBox change event.
// Calls the countLast() function to count the
// number of items to the end of the collection.
public function countFromSelection():void {
myCursor.findFirst(myCB.selectedItem);
var count:int = countLast(myCursor);
184 Using Data Providers and Collections
ta1.text += myCursor.current.label + " is " + count +
" from the last item.\n";
}
]]>
</mx:Script>
<!-- The data provider, an ArrayCollection with an array of objects. -->
<mx:ArrayCollection id="myAC">
<mx:Object label="MA" data="Boston"/>
<mx:Object label="ME" data="Augusta"/>
<mx:Object label="MI" data="Lansing"/>
<mx:Object label="MN" data="Saint Paul"/>
<mx:Object label="MO" data="Jefferson City"/>
<mx:Object label="MS" data="Jackson"/>
<mx:Object label="MT" data="Helena"/>
</mx:ArrayCollection>
<mx:ComboBox id="myCB" rowCount="7" dataProvider="{myAC}"
change="countFromSelection();"/>
<mx:TextArea id="ta1" height="200" width="175"/>
</mx:Application>
Example: Updating an Array Using ICollectionView
interface methods and properties
The following example uses the ICollectionView methods and properties of an
ArrayCollection object to display an array with the following elements in a ComboBox
control:
"AZ", "MA", "MZ", "MN", "MO", "MS"
When you click the Update View button, the application uses the length property and
several methods of the ICollectionView interface to do the following:
■ Changes the data in the array and the displayed data in the ComboBox control to a
correct alphabetical list of the U.S. ZIP codes for states that start with M:
MA, ME, MI, MN, MO, MS, MT
■ Saves a bookmark that points to the ME item that it adds, and later restores the cursor to
this position.
■ Displays in a TextArea control information about the tasks it performed and the resulting
array.
When you click the Sort button, the application reverses the order of the items in the view,
and limits the viewed range to ME–MO.
Using ICollectionView interface methods and properties 185
When you click the Reset button, the application resets the data provider array and the
collection view.
<?xml version="1.0"?>
<!-- dpcontrols\UpdateArrayViaICollectionView.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="initData();">
<mx:Script>
<![CDATA[
import mx.collections.*;
// The data provider is an array of Strings.
public var myArray:Array = ["AZ", "MA", "MZ", "MN", "MO", "MS"];
// Declare an ArrayCollection that represents the Array.
// The variable must be bindable so the ComboBox can update
properly.
[Bindable]
public var myAC:ArrayCollection;
//Boolean flag to ensure the update routine hasn't been run
before.
public var runBefore:Boolean=false;
//Initialize the ArrayCollection the application initializes.
public function initData():void {
myAC = new ArrayCollection(myArray);
}
// The function to change the collection.
public function changeCollection():void {
//Running this twice without resetting causes an error.
if (! runBefore) {
runBefore=true;
// Get an IViewCursor object for accessing the collection
data.
var myCursor:IViewCursor=myAC.createCursor();
// Get the original collection length.
var oldLength:int=myAC.length;
// The cursor is initially at the first item; delete it.
var removedItem:String=String(myCursor.remove());
// Add ME as the second item.
// The cursor is at the (new) first item;
// move it to the second item.
myCursor.moveNext();
// Insert ME before the second item.
myCursor.insert("ME");
// Add MT at the end of the collection.
//Use the LAST bookmark property to go to the end of the
186 Using Data Providers and Collections
view.
// Add an offset of 1 to position the cursor after the
last item.
myCursor.seek(CursorBookmark.LAST, 1);
myCursor.insert("MT");
// Change MZ to MI.
// The findFirst() method requires a sorted view.
var sort:Sort = new Sort();
myAC.sort=sort;
// Refresh the collection view to apply the sort.
myAC.refresh();
// Make sure there is a MZ item, and no MI in the array.
if (myCursor.findFirst("MZ") &&
!myCursor.findFirst("MI")) {
// The IViewCursor does not have a replace operation.
// First, remove "MZ".
myCursor.remove();
// Because the view is now sorted, the insert puts
this item
// in the right place in the sorted view, but at the
end of
// the underlying Array data provider.
myCursor.insert("MI");
}
// Get the updated collection length.
var newLength:int=myAC.length;
// Set a bookmark at the item with the value ME,
myCursor.findFirst("ME");
var MEMark:CursorBookmark=myCursor.bookmark;
// Move the cursor to the last item in the Array.
myCursor.seek(CursorBookmark.LAST);
// Get the last item in the collection.
var lastItem:String=String(myCursor.current);
// Return the cursor to the bookmark position.
myCursor.seek(MEMark);
// Get the item at the cursor location.
var MEItem:String=String(myCursor.current);
// Display the information in the TextArea control.
ta1.text="Start Length: " + oldLength + ". End Length: "
+ newLength;
ta1.text+=".\nRemoved " + removedItem;
ta1.text+=".\nLast Item is " + lastItem;
ta1.text+=".\nItem at MEMark is " + MEItem;
// Show that the base Array has been changed.
// Notice that the Array is NOT in sorted order.
ta1.text+="\nThe base Array is: " + myArray.join();
} // End runBefore condition
Using ICollectionView interface methods and properties 187
}
// Filter function used in the sortICV method to limit the range.
public function MEMOFilter(item:Object):Boolean {
return item >= "ME" && item <= "MO";
}
// Sort the collection view in descending order,
// and limit the items to the range ME - MO.
public function sortICV():void {
var sort:Sort = new Sort();
sort.fields=[new SortField(null, false, true)];
myAC.filterFunction=MEMOFilter;
myAC.sort=sort;
// Refresh the ArrayCollection to apply the sort and filter
// function.
myAC.refresh();
//Call the ComboBox selectedIndex() method to replace the
"MA"
//in the display with the first item in the sorted view.
myCB.selectedIndex=0;
ta1.text="Sorted";
}
//Reset the Array and update the display to run the example
again.
public function resetView():void {
myArray = ["AZ", "MA", "MZ", "MN", "MO", "MS"];
myAC = new ArrayCollection(myArray);
ta1.text="Reset";
runBefore=false;
}
]]>
</mx:Script>
<mx:ComboBox id="myCB" rowCount="7" dataProvider="{myAC}"/>
<mx:TextArea id="ta1" height="75" width="300"/>
<mx:HBox>
<mx:Button label="Update View" click="changeCollection();"/>
<mx:Button label="Sort View" click="sortICV();"/>
<mx:Button label="Reset View" click="resetView();"/>
</mx:HBox>
</mx:Application>
188 Using Data Providers and Collections
Using events and update notifications
The Flex collection mechanism includes events that represent changes to the collection and
provides methods to control the delivery of events. The following sections describe these
events, and discuss the ways you can control event delivery.
Using collection events
Flex includes several classes that you use in collection-related events:
■ Classes that implement the IList or ICollectionView interface dispatch a CollectionEvent
(mx.events.CollectionEvent) class event whenever the collection changes. All collection
events have the type property value CollectionEvent.COLLECTION_CHANGE.
■ The CollectionEvent object includes a kind property that indicates the way in which the
collection changed; you can determine the change by comparing the kind property value
with the CollectionEventKind constants, for example, UPDATE.
■ The CollectionEvent object includes an items property that is an Array of objects whose
type varies depending on the event kind. For ADD and REMOVE kind events, the array
contains the added or removed items. For UPDATE events, the items property contains
an Array of PropertyChangeEvent event objects. This object’s properties indicate the type
of change and the property value before and after the change.
■ The PropertyChangeEvent class kind property indicates the way in which the property
changed; you can determine the change type by comparing the kind property value with
the PropertyChangeEventKind constants, for example, UPDATE.
■ Classes that implement the IViewCursor interface dispatch a FlexEvent class event with a
type of the type property value of mx.events.FlexEvent.CURSOR_UPDATE when the
cursor position changes.
You use collection events to monitor changes to a collection to update the display. For
example, if a custom control uses a collection as its data provider, and you want the control to
update dynamically and display the revised data each time the collections changes, the control
can monitor the collection events and update accordingly.
You could, for example, build a simple rental-car reservation system that uses collection
events. This application uses COLLECTION_CHANGE event type listeners for changes to its
reservations and cars data collections.
Using events and update notifications 189
The CollectionEvent listener method, named reservationsChanged, tests the event kind
field and does the following:
■ If the event kind property is ADD, iterates through the objects in the event’s items
property and calls a function to update the reservation information display with boxes that
display the time span of each reservation.
■ If the event kind property is REMOVE, iterates through the objects in the event’s items
property and calls a function to remove the reservation box for each item.
■ If the event kind property is UPDATE, iterates through the PropertyChangeEvent objects
in the event’s items property and calls the update function to update each item.
■ If the event kind property is RESET, calls a function to reset the reservation information.
The following examples shows the reservationsChanged CollectionEvent event listener
function:
private function reservationsChanged(event:CollectionEvent):void {
switch (event.kind) {
case CollectionEventKind.ADD:
for (var i:uint = 0; i < event.items.length; i++) {
updateReservationBox(Reservation(event.items[i]));
}
break;
case CollectionEventKind.REMOVE:
for (var i:uint = 0; i < event.items.length; i++) {
removeReservationBox(Reservation(event.items[i]));
}
break;
case CollectionEventKind.UPDATE:
for (var i:uint = 0; i < event.items.length; i++) {
if (event.items[i] is PropertyChangeEvent) {
if (PropertyChangeEvent(event.items[i]) != null) {
updateReservationBox(Reservation(PropertyChangeEvent(
event.items[i]).source));
}
}
else if (event.items[i] is Reservation) {
updateReservationBox(Reservation(event.items[i]));
}
}
break;
case CollectionEventKind.RESET:
refreshReservations();
break;
}
}
190 Using Data Providers and Collections
The updateReservationBox() method either shows or hides a box that shows the time span
of the reservation. The removeReservationBox() method removes a reservation box. The
refreshReservations() method redisplays all current reservation information.
For more information on the application and the individual methods, see the sample code.
Using collection change notifications
The IList and ICollectionView interfaces include the itemUpdated() method that notifies
the collection that the underlying data has changed and ensures that the collection view of the
data is up to date. This method takes the item that was modified, the property in the item
that was updated, and its old and new values as parameters.
The ICollectionView interface also provides the enableAutoUpdate() and
disableAutoUpdate() methods, which enable and disable the automatic updating of the
collection view when the underlying data provider changes.
Using the itemUpdated method
Use the itemUpdated() method to notify the collection of changes to a data provider object
if the object does not implement the IEventDispatcher interface; in this case the object is not
monitorable. Flash and Flex Objects and other basic data types do not implement this
interface. Therefore, You must use the itemUpdated method to update the collection when
you modify the properties of a data provider such as an Array or through the display object.
You can also use the itemUpdated() method if you must use an Array, rather than a
collection, as a control’s data provider. Then the component wraps the Array in a collection
wrapper. The wrapper needs to be manually notified of any changes made to the underlying
Array data object, and you can use the itemUpdated() for that notification.
You do not have to use the itemUpdated() method if you add or remove items directly in a
collection or use any of the ICollectionView or IList methods to modify the collection.
Using events and update notifications 191
Also, specifying the [Bindable] metadata tag above a class definition, or above a variable
declaration within the class ensures that the class implements the IEventDispatcher interface,
and causes the class to dispatch propertyChange events. If you specify the [Bindable] tag
above the class declaration, the class dispatches propertyChange events for all properties; if
you mark only specific properties as [Bindable], the class dispatches events for only those
properties. The collection listens for the propertyChange events. Therefore, if you have a
collection called myCollection that consists of instances of a class that has a [Bindable]
myVariable variable, an expression such as
myCollection.getItemAt(0).myVariable="myText" causes the item to dispatch an event
and you do not have to use the itemUpdated() method. (For more information on the
[Bindable] metadata tag and its use, see Chapter 38, “Binding Data,” on page 1245.)
The most common use for the itemUpdate() method is to notify a collection of changes to a
custom class data source that you cannot make [Bindable] or modify to implement the
IEventDispatcher interface. The following schematic example shows how you could use the
itemUpdated() method in such a circumstance:
Assume you have a class that you do not control or edit that looks like the following:
public class ClassICantEdit {
public var field1:String;
public var field2:String;
}
You have an ArrayCollection that uses these object, such as the following, which you populate
with classICantEdit objects.
public var myCollection:ArrayCollection = new ArrayCollection();
You have DataGrid control such as the following
<mx:DataGrid dataProvider="{myCollection}"/>
When you update a field in the myCollection ArrayCollection, as follows, the DataGrid
does not automatically update.
myCollection.getItemAt(0).field1="someOtherValue";
To update the DataGrid control, you must use the collection’s itemUpdated() method:
myCollection.itemUpdated(collectionOfThoseClasses.getItemAt(0));
Disabling and enabling automatic updating
The ICollectionView disableAutoUpdate() method prevents events that represent changes
to the underlying data from being broadcast by the view. It also prevents the ICollectionView
from updating as a result of these changes.
192 Using Data Providers and Collections
Use this method to prevent the ICollectionView, and therefore the control that uses it as a
DataProvider, from showing intermediate changes in a set of multiple changes. The DataGrid
class, for example, uses the disableAutoUpdate() method to prevent updates to the
ICollectionView object while a specific item is selected. When the item is no longer selected,
the DataGrid calls the enableAutoUpdate() method. Doing this ensures that, if a DataGrid
uses a sorted collection view, items that you edit do not jump around while you’re editing.
You can also use the disableAutoUpdate() method to optimize performance in cases where
multiple items in a collection are being edited at once. By disabling the auto update until all
changes are made, a control like DataGrid can receive an update event as a single batch
instead of reacting to multiple events.
The following code snippet shows the use of the disableAutoUpdate() and
enableAutoUpdate() methods:
var obj:myObject = myCollection.getItemAt(0);
myCollection.disableAutoUpdate();
obj.prop1 = 'foo';
obj.prop2 = 'bar';
myCollection.enableAutoUpdate();
Using events and update notifications 193
Example: Modifying data in DataGrid control
The following example lets you add, remove, or modify data in a DataGrid control.
<?xml version="1.0"?>
<!-- dpcontrols\ModifyDataGridData.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="500"
height="600" >
<mx:Script>
<![CDATA[
import mx.events.*;
import mx.collections.*;
// Add event information to a log (displayed in the TextArea).
public function
collectionEventHandler(event:CollectionEvent):void {
switch(event.kind) {
case CollectionEventKind.ADD:
addLog("Item "+ event.location + " added");
break;
case CollectionEventKind.REMOVE:
addLog("Item "+ event.location + " removed");
break;
case CollectionEventKind.REPLACE:
addLog("Item "+ event.location + " Replaced");
break;
case CollectionEventKind.UPDATE:
addLog("Item updated");
break;
}
}
// Helper function for adding information to the log.
public function addLog(str:String):void {
log.text += str + "\n";
}
// Add a person to the ArrayCollection.
public function addPerson():void {
ac.addItem({first:firstInput.text, last:lastInput.text,
email:emailInput.text});
clearInputs();
}
// Remove a person from the ArrayCollection.
public function removePerson():void {
// Make sure an item is selected.
if (dg.selectedIndex >= 0) {
ac.removeItemAt(dg.selectedIndex);
}
194 Using Data Providers and Collections
}
// Update an existing person in the ArrayCollection.
public function updatePerson():void {
// Make sure an item is selected.
if (dg.selectedItem !== null) {
ac.setItemAt({first:firstInput.text, last:lastInput.text,
email:emailInput.text}, dg.selectedIndex);
}
}
// The change event listener for the DataGrid.
// Clears the text input controls and updates them with the contents
// of the selected item.
public function dgChangeHandler():void {
clearInputs();
firstInput.text = dg.selectedItem.first;
lastInput.text = dg.selectedItem.last;
emailInput.text = dg.selectedItem.email;
}
// Clear the text from the input controls.
public function clearInputs():void {
firstInput.text = "";
lastInput.text = "";
emailInput.text = "";
}
// The labelFunction for the ComboBox;
// Puts first and last names in the ComboBox.
public function myLabelFunc(item:Object):String {
return item.first + " " + item.last;
}
]]>
</mx:Script>
<!-- The ArrayCollection used by the DataGrid and ComboBox. -->
<mx:ArrayCollection id="ac"
collectionChange="collectionEventHandler(event)">
<mx:source>
<mx:Object first="Matt" last="Matthews" email="
[email protected]"/>
<mx:Object first="Sue" last="Sanderson" email="
[email protected]"/>
<mx:Object first="Harry" last="Harrison" email="
[email protected]"/
>
</mx:source>
</mx:ArrayCollection>
<mx:DataGrid width="450" id="dg" dataProvider="{ac}"
change="dgChangeHandler()">
<mx:columns>
Using events and update notifications 195
<mx:DataGridColumn dataField="first" headerText="First Name"/>
<mx:DataGridColumn dataField="last" headerText="Last Name"/>
<mx:DataGridColumn dataField="email" headerText="Email"/>
</mx:columns>
</mx:DataGrid>
<!-- The ComboBox and DataGrid controls share an ArrayCollection as
their
data provider.
The ComboBox control uses the labelFunction property to construct
the
labels from the dataProvider fields. -->
<mx:ComboBox id="cb" dataProvider="{ac}" labelFunction="myLabelFunc"/>
<!-- Form for data to add or change in the ArrayCollection. -->
<mx:Form>
<mx:FormItem label="First Name">
<mx:TextInput id="firstInput"/>
</mx:FormItem>
<mx:FormItem label="Last Name">
<mx:TextInput id="lastInput"/>
</mx:FormItem>
<mx:FormItem label="Email">
<mx:TextInput id="emailInput"/>
</mx:FormItem>
</mx:Form>
<mx:HBox>
<!-- Buttons to initiate operations on the collection. -->
<mx:Button label="Add New" click="addPerson()"/>
<mx:Button label="Update Selected" click="updatePerson()"/>
<mx:Button label="Remove Selected" click="removePerson()"/>
<!-- Clear the text input fields. -->
<mx:Button label="Clear" click="clearInputs()"/>
</mx:HBox>
<!-- The application displays event information here -->
<mx:Label text="Log"/>
<mx:TextArea id="log" width="100" height="100%"/>
</mx:Application>
196 Using Data Providers and Collections
Using hierarchical data providers
You use hierarchical data providers with the controls that display a nested hierarchy of nodes
and subnodes, such as tree branches and leaves and Menu submenus and items. The following
controls take hierarchical data providers:
■ Menu
■ MenuBar
■ PopUpMenuButton
■ Tree
The hierarchical components all use the same mechanism to work with the data provider. The
examples in this section use the Tree control but also apply to the other components also.
About hierarchical data providers
The Flex framework, by default, supports two types of hierarchical data sources:
XML can be any of the following: Strings containing well-formed XML; or XML, XMLList,
or XMLListCollection objects, including objects generated by the <mx:XML> and
<mx:XMLList> compile-time tags. (These tags support data binding, which you cannot do
directly in ActionScript.) Flex can automatically structure a Tree or menu-based control to
reflect the nesting hierarchy of well-formed XML.
Objects can be any set of nested Objects or Object subclasses (including Arrays or
ArrayCollection objects) having a structure where the children of a node are in a children
field. For more information, see “Creating a custom data descriptor”. You can also use the
<mx:Model> compile-time tag to create nested objects that support data binding, but you
must follow the structure defined in “Using the <mx:Model> tag with Tree and menu-based
controls” on page 200.
You can add support for other hierarchical data provider structures, such as nested Objects
where the children might be in fields with varying names.
Data descriptors and hierarchical data provider
structure
Hierarchical data used in Tree and menu-based controls must be in a form that can be parsed
and manipulated using a data descriptor class. A data descriptor is a class that provides an
interface between the hierarchical control and the data provider object. It implements a set of
control-specific methods to determine the data provider contents and structure, and to get,
add, and remove data, and to change control-specific data properties.
Using hierarchical data providers 197
Flex defines two data descriptor interfaces for hierarchical controls:
ITreeDataDescriptor Methods used by Tree controls
IMenuDataDescriptor Methods for Menu, MenuBar, and PopUpMenuButton controls
The Flex framework provides a DefaultDataDescriptor class that implements both interfaces.
You can use the dataDescriptor property to specify a custom data descriptor class that
handles data models that do not conform to the default descriptor structure.
Data descriptor methods and source requirements
The following table describes the methods of both interfaces, and the behavior of the
DefaultDataDescriptor class. The first line of each Interface/Method entry indicates whether
the method belongs to the ITreeDataDescriptor interface, IMenuDataDescriptor interface, or
both interfaces, and therefore indicates whether the method is used for trees, menus, or both.
Interface/ Returns DefaultDataDescriptor behavior
Method
Both Boolean value For XML, returns true if the node has at least one
hasChildrent(node, indicating whether child element.
[model]) the node a branch For other objects, returns true if the node has a
with children. non-empty children field.
Both A node’s children. For XML, returns an XMLListCollection with the
getChildren(node, child elements.
[collection]) For other Objects, returns the contents of the
node’s children field.
Both Whether a node is For XML, returns true if the node has at least one
isBranch(node, a branch. child, or if it has an isBranch attribute.
[collection]) For other Objects, returns true if the node has an
isBranch field.
Both The node data. Returns the node.
getData(node,
[collection])
Both Boolean value For all cases, inserts the node as a child object
addChildAt(node, indicating whether before the node currently in the index location.
child, index, [model]) the operation
succeeded.
Both Boolean value For all cases, removes the child of the node in the
removeChildAt indicating whether index location.
(node, index, [model]) the operation
succeeded.
198 Using Data Providers and Collections
Interface/ Returns DefaultDataDescriptor behavior
Method
IMenuDataDescriptor A String with the For XML, returns the value of the type attribute of
getType(node) menu node type, the node.
Meaningful values For other Objects, returns the contents of the
are check, radio, node’s type field.
and separator.
IMenuDataDescriptor Boolean value For XML, returns the value of the enabled attribute
isEnabled(node) indicating if a of the node.
menu node is For other Objects, returns the contents of the
enabled. node’s enabled field.
IMenuDataDescriptor For XML, sets the value of the enabled attribute of
setEnabled(node, the node to true or false.
value) For other Objects, sets the contents of the node’s
enabled field.
IMenuDataDescriptor Boolean value For XML, returns the value of the selected
isToggled(node) indicating if a attribute of the node.
menu node is For other Objects, returns the contents of the
selected node’s enabled field.
IMenuDataDescriptor For XML, sets the value of the selected attribute
setToggled(node, of the node to true or false.
value) For other Objects, sets the contents of the node’s
enabled field.
IMenuDataDescriptor The name of the For XML, returns the value of the groupName
getGroupName radio button group attribute of the node.
(node) to which the node For other Objects, returns the contents of the
belongs. node’s groupName field.
The following example Object follows the default data provider structure for a Tree control,
and is correctly handled by the DefaultDataDescriptor class:
[Bindable]
public var fileSystemStructure:Object =
{label:"mx", children: [
{label:"Containers", children: [
{label:"Accordian", children:[]},
{label:"DividedBox", children: [
{label:"BoxDivider.as", data:"BoxDivider.as"},
{label:"BoxUniter.as", data:"BoxUniter.as"}]},
{label: "Grid", children:[]}]},
{label: "Controls", children: [
{label: "Alert", data: "Alert.as"},
{label: "Styles", children: [
{label: "AlertForm.as", data:"AlertForm.as"}]},
Using hierarchical data providers 199
{label: "Tree", data: "Tree.as"},
{label: "Button", data: "Button.as"}]},
{label: "Core", children:[]}
]};
For objects, the root is the Object instance, so there must always a single root (as with XML).
You could also use an Array containing nested Arrays as the data provider; in this case the
provider has no root; each element in the top level array appears at the top level of the control.
The DefaultDataDescriptor can properly handle well formed XML nodes. The isBranch()
method, however, returns true only if the parameter node has child nodes or if the node has
an isBranch attribute with the value true. If your XML object uses any technique other than
a true isBranch attribute to indicate empty branches, you must therefore create a custom
data descriptor.
The DefaultDataDescriptor handles collections properly. For example, if a node’s children
property is an ICollectionView, the getChildren() method returns the children as an
ICollectionView object.
Using the <mx:Model> tag with Tree and menu-based controls
The <mx:Model> tag lets you define a data provider structure in MXML. The Flex compiler
converts the contents of the tag into a hierarchical graph of ActionScript Objects. The
<mx:Model> tag has two advantages over defining an Object data provider in ActionScript:
■ You can define the structure using an easily read, XML-like format.
■ You can bind structure entries to ActionScript variables, so you can use the <mx:Model> to
create an object-based data provider that gets its data from multiple dynamic sources.
To use an <mx:Model> tag with a control that uses a data descriptor, the object generated by
the compiler must conform to the data descriptor requirements, as discussed in “Data
descriptors and hierarchical data provider structure” on page 197. Also, as with an XML
object, the tag must have a single root element.
In most situations, you should consider using an <mx:XML> or <mx:XMLList> tag, as
described in “Using an XML data provider” on page 209, instead of using an <mx:Model> tag.
The XML-based tags support data binding to elements, and the DefaultDataDescriptor class
supports all well-structured XML. Therefore, you can use a more natural structure, where
node names can represent their function, and you do not have to artificially name nodes
“children.”
To use the an <mx:Model> tag as the data provider for a control that uses
DefaultDataDescriptor class, all child nodes must be named “children.” This requirement
differs from the structure that you use with an Object, where the array that contains the child
objects is named children.
200 Using Data Providers and Collections
The following example shows the use of an <mx:Model> tag with data binding as a data
provider for a menu, and shows how you can change the menu structure dynamically:
<?xml version="1.0"?>
<!-- dpcontrols\ModelWithMenu.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*">
<mx:Script>
<![CDATA[
import mx.controls.Menu;
public var productMenu:Menu;
public function initMenu(): void
{
productMenu = Menu.createMenu(null, Products.Department);
productMenu.setStyle("disabledColor", 0xCC3366);
productMenu.show(10,10);
}
]]>
</mx:Script>
<mx:Model id="Products">
<Root>
<Department label="Toys">
<children label="Care Bear"/>
<children label="GI Joe"/>
<children label="Telly Tubbies"/>
</Department>
<Department label="Kitchen">
<children label="Electronics">
<children label="Crock Pot"/>
<children label="Panini Grill"/>
</children>
<children label="Cookware">
<children label="Grill Pan"/>
<children label="Iron Skillet" enabled="false"/>
</children>
</Department>
<!-- The items in this entry are bound to the form data -->
<Department label="{menuName.text}">
<children label="{item1.text}"/>
<children label="{item2.text}"/>
<children label="{item3.text}"/>
</Department>
</Root>
</mx:Model>
<mx:Button label="Show Products" click="initMenu()"/>
<!-- If you change the contents of the form, the next time you
Using hierarchical data providers 201
display the Menu, it will show the updated data in the last
main menu item. -->
<mx:Form>
<mx:FormItem label="Third Submenu title">
<mx:TextInput id="menuName" text="Clothing"/>
</mx:FormItem>
<mx:FormItem label="Item 1">
<mx:TextInput id="item1" text="Sweaters"/>
</mx:FormItem>
<mx:FormItem label="Item 2">
<mx:TextInput id="item2" text="Shoes"/>
</mx:FormItem>
<mx:FormItem label="Item 3">
<mx:TextInput id="item3" text="Jackets"/>
</mx:FormItem>
</mx:Form>
</mx:Application>
Creating a custom data descriptor
If your hierarchical data does not fit the formats supported by the DefaultDataDescriptor
class, for example if your data is in an object that does not use a children field, you can write a
custom data descriptor and specify it in your Tree control’s dataDescriptor property. The
custom data descriptor must implement all methods of the ITreeDataDescriptor interface.
The following example shows how you can create a custom data descriptor, in this case, for
use with a Tree control. This data descriptor correctly handles a data provider that consists of
nested ArrayCollection objects.
202 Using Data Providers and Collections
The following code shows the MyCustomTreeDataDescriptor class, which implements only
the ITreeDataDescriptor interface, so it supports Tree controls, but not menu-based controls.
The custom class supports tree nodes whose children field is either an ArrayCollection or an
Object. When getting a node’s children, if the children object is an ArrayCollection, it returns
the object; otherwise, it wraps the children object in an ArrayCollection before returning it.
When adding a node, it uses a different method to add the node, depending on the children
field type.
package myComponents
// myComponents/MyCustomTreeDataDescriptor.as
{
import mx.collections.ArrayCollection;
import mx.collections.CursorBookmark;
import mx.collections.ICollectionView;
import mx.collections.IViewCursor;
import mx.events.CollectionEvent;
import mx.events.CollectionEventKind;
import mx.controls.treeClasses.*;
public class MyCustomTreeDataDescriptor implements ITreeDataDescriptor
{
// The getChildren method requires the node to be an Object
// with a children field.
// If the field contains an ArrayCollection, it returns the field
// Otherwise, it wraps the field in an ArrayCollection.
public function getChildren(node:Object,
model:Object=null):ICollectionView
{
try
{
if (node is Object) {
if(node.children is ArrayCollection){
return node.children;
}else{
return new ArrayCollection(node.children);
}
}
}
catch (e:Error) {
trace("[Descriptor] exception checking for getChildren");
}
return null;
}
// The isBranch method simply returns true if the node is an
// Object with a children field.
// It does not support empty branches, but does support null children
// fields.
Using hierarchical data providers 203
public function isBranch(node:Object, model:Object=null):Boolean {
try {
if (node is Object) {
if (node.children != null) {
return true;
}
}
}
catch (e:Error) {
trace("[Descriptor] exception checking for isBranch");
}
return false;
}
// The hasChildren method Returns true if the
// node actually has children.
public function hasChildren(node:Object, model:Object=null):Boolean {
if (node == null)
return false;
var children:ICollectionView = getChildren(node, model);
try {
if (children.length > 0)
return true;
}
catch (e:Error) {
}
return false;
}
// The getData method simply returns the node as an Object.
public function getData(node:Object, model:Object=null):Object {
try {
return node;
}
catch (e:Error) {
}
return null;
}
// The addChildAt method does the following:
// If the parent parameter is null or undefined, inserts
// the child parameter as the first child of the model parameter.
// If the parent parameter is an Object and has a children field,
// adds the child parameter to it at the index parameter location.
// It does not add a child to a terminal node if it does not have
// a children field.
public function addChildAt(parent:Object, child:Object, index:int,
model:Object=null):Boolean {
var event:CollectionEvent = new
CollectionEvent(CollectionEvent.COLLECTION_CHANGE);
event.kind = CollectionEventKind.ADD;
204 Using Data Providers and Collections
event.items = [child];
event.location = index;
if (!parent) {
var iterator:IViewCursor = model.createCursor();
iterator.seek(CursorBookmark.FIRST, index);
iterator.insert(child);
}
else if (parent is Object) {
if (parent.children != null) {
if(parent.children is ArrayCollection) {
parent.children.addItemAt(child, index);
if (model){
model.dispatchEvent(event);
model.itemUpdated(parent);
}
return true;
}
else {
parent.children.splice(index, 0, child);
if (model)
model.dispatchEvent(event);
return true;
}
}
}
return false;
}
// The removeChildAt method does the following:
// If the parent parameter is null or undefined,
// removes the child at the specified index
// in the model.
// If the parent parameter is an Object and has a children field,
// removes the child at the index parameter location in the parent.
public function removeChildAt(parent:Object, child:Object, index:int,
model:Object=null):Boolean
{
var event:CollectionEvent = new
CollectionEvent(CollectionEvent.COLLECTION_CHANGE);
event.kind = CollectionEventKind.REMOVE;
event.items = [child];
event.location = index;
//handle top level where there is no parent
if (!parent)
{
var iterator:IViewCursor = model.createCursor();
iterator.seek(CursorBookmark.FIRST, index);
iterator.remove();
if (model)
Using hierarchical data providers 205
model.dispatchEvent(event);
return true;
}
else if (parent is Object)
{
if (parent.children != undefined)
{
parent.children.splice(index, 1);
if (model)
model.dispatchEvent(event);
return true;
}
}
return false;
}
}
}
206 Using Data Providers and Collections
The following example uses the MyCustomTreeDataDescriptor to handle hierarchical nested
ArrayCollections and objects. When you click the button it adds a node to the tree by calling
the data descriptor’s addChildAt() method. Notice that you would not normally use the
addChildAt() method directly. Instead, you would use the methods of a Tree or menu-based
control, which, in turn, use the data descriptor methods to modify the data provider.
<?xml version="1.0" encoding="iso-8859-1"?>
<!-- dpcontrols\CustDataDescriptor.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*"
creationComplete="initCollections()">
<mx:Script>
<![CDATA[
import mx.collections.*;
import mx.controls.treeClasses.*;
import myComponents.*;
//Variables used to construct the ArrayCollection data provider
//First top-level node and its children.
public var nestArray1:Array = [
{label:"item1", children: [
{label:"item1 child", children: [
{label:"item 1 child child", data:"child data"}
]}
]}
];
//Second top-level node and its children.
public var nestArray2:Array = [
{label:"item2", children: [
{label:"item2 child", children: [
{label:"item 2 child child", data:"child data"}
]}
]}
];
//Second top-level node and its children.
public var nestArray3:Array = [
{label:"item3", children: [
{label:"item3 child", children: [
{label:"item 3 child child", data:"child data"}
]}
]}
];
//Variable for the tree array.
public var treeArray:Array
//Variables for the three Array collections that correspond to
the
//top-level nodes.
public var col1:ArrayCollection;
public var col2:ArrayCollection;
Using hierarchical data providers 207
public var col3:ArrayCollection;
//Variable for the ArrayCollection used as the Tree data
provider.
[Bindable]
public var ac:ArrayCollection;
//build the ac ArrayCollection from its parts.
public function initCollections():void{
// Wrap each top-level node in an ArrayCollection.
col1 = new ArrayCollection(nestArray1);
col2 = new ArrayCollection(nestArray2);
col3 = new ArrayCollection(nestArray3);
// Put the three top-level node
// ArrayCollections in the treeArray.
treeArray = [
{label:"first thing", children: col1},
{label:"second thing", children: col2},
{label:"third thing", children: col3},
];
//Wrap the treeArray in an ArrayCollection.
ac = new ArrayCollection(treeArray);
}
// Adds a child node as the first child of the selected node,
// if any. The default selectedItem is null, which causes the
// data descriptor addChild method to add it as the first child
// of the ac ArrayCollection.
public function clickAddChildren():void {
var newChild:Object = new Object();
newChild.label = "New Child";
newChild.children = new ArrayCollection();
tree.dataDescriptor.addChildAt(tree.selectedItem, newChild,
0, ac);
}
]]>
</mx:Script>
<mx:Tree width="200" id="tree" dataProvider="{ac}"
dataDescriptor="{new MyCustomTreeDataDescriptor()}"/>
<mx:Button label="add children" click="clickAddChildren()"/>
</mx:Application>
208 Using Data Providers and Collections
Using an XML data provider
Often, the data for a tree is retrieved from a server in the form of XML, but it can also be well-
formed XML defined within the <mx:Tree> tag. The DefaultDataDescriptor class can handle
well-formed XML data providers.
You can use an <mx:XML> or <mx:XMLList> tag to define an XML or XMLList object in
MXML. Unlike the XML and XMLList classes in ActionScript, these tags let you use MXML
binding expressions in the XML text to extract node contents from variable data. For
example, you can bind a node's name attribute to a text input value, as in the following
example:
<mx:XMLList id="myXMLList">
<child name="{textInput1.text}"/>
<child name="{textInput2.text}"/>
</mx:XMLList>
You can use an XML object directly as a dataProvider to a hierarchical data control. However,
if the object changes dynamically, you should do the following:
1. Convert the XML or XMLList object to an XMLListCollection object.
2. Make all update to the data by modifying the XMLListCollection object.
Doing this ensures that the component represents the dynamic data. The XMLListCollection
class supports the use of all IList and ICollectionView interface methods, and adds many of
the most commonly used XMLList class methods. For more information on using
XMLListCollections see “Using the XMLListCollection class” on page 211.
Using hierarchical data providers 209
The following code example defines two Tree controls; the first uses an XML object directly,
the second uses an XMLListCollection object as the data source:
<?xml version="1.0"?>
<!-- dpcontrols\UseXMLDP.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:XML id="capitals">
<root>
<Capitals label="U.S. State Capitals">
<capital label="AL" value="Montgomery"/>
<capital label="AK" value="Juneau"/>
<capital label="AR" value="Little Rock"/>
<capital label="AZ" value="Phoenix"/>
</Capitals>
<Capitals label="Canadian Province Capitals">
<capital label="AB" value="Edmonton"/>
<capital label="BC" value="Victoria"/>
<capital label="MB" value="Winnipeg"/>
<capital label="NB" value="Fredericton"/>
</Capitals>
</root>
</mx:XML>
<!-- Create an XMLListCollection representing the Tree nodes.
capitals.Capitals is an XMLList with both Capitals elements. -->
<mx:XMLListCollection id="capitalColl" source="{capitals.Capitals}"/>
<!-- When you use an XML-based data provider with a tree
you must specify the label field, even if it
is "label". The XML object includes the root,
so you must set showRoot="false". Remember that
the Tree will not, by default, reflect dynamic changes
to the XML object. -->
<mx:Tree id="Tree1" dataProvider="{capitals}" labelField="@label"
showRoot="false" width="300"/>
<!-- The XMLListCollection does not include the XML root. -->
<mx:Tree id="Tree2" dataProvider="{capitalColl}" labelField="@label"
width="300"/>
</mx:Application>
210 Using Data Providers and Collections
This example shows two important features when using a hierarchical data provider with a
Tree control:
■ ECMAScript for XML (E4X) objects must have a single root node, which might not
appropriate for displaying in the Tree. Also, trees, can have multiple elements at their
highest level. To prevent the tree from displaying the root node, specify the showRoot
property to false. (The default showRoot value for the Tree control is true.) XMLList
collections, however, do not have a single root, and you typically do not need to use the
showRoot property.
■ When you use an XML, XMLList, or XMLListCollection object as the tree data provider,
you must specify the labelField property, even if it is “label”, if the field is an XML
attribute. You must do this because you must use the @ sign to signify an attribute.
Using the XMLListCollection class
The XMLListCollection class provides collection functionality to an XMLList object and
makes available some of the XML manipulation methods of the native XMLList class, such as
the attributes(), children(), and elements(). For details of the supported methods, see
XMLListCollection in Adobe Flex 2 Language Reference.
The following simple example uses an XMLListCollection object as the data provider for a
List control. It uses XMLListCollection methods to dynamically add and remove items from
the data provider and its representation in the List control. The example uses a Tree control to
represent a selection of shopping items and a List collection to represent a shopping list.
Users add items to the List control by selecting an item in a Tree control (which uses a static
XML object as its data provider) and clicking a button. When the user clicks the button, the
event listener uses the XMListCollection addItem() method to add the selected XML node
to the XMLListCollection. Because the data provider is a collection, the List control updates
to show the new data.
Using hierarchical data providers 211
Users remove items in a similar manner, by selecting an item in the list and clicking a Remove
button. The event listener uses the XMListCollection removeItemAt() method to remove
the item from the data provider and its representation in the List control.
<?xml version="1.0"?>
<!-- dpcontrols\XMLListCollectionWithList.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" height="400">
<mx:Script>
<![CDATA[
import mx.collections.XMLListCollection;
import mx.collections.ArrayCollection;
// An XML object with categorized produce.
[Bindable]
public var myData:XML=
<catalog>
<category name="Meat">
<product name="Buffalo" cost="4" isOrganic="No"
isLowFat="Yes"/>
<product name="T Bone Steak" cost="6" isOrganic="No"
isLowFat="No"/>
<product name="Whole Chicken" cost="1.5"
isOrganic="Yes"
isLowFat="No"/>
</category>
<category name="Vegetables">
<product name="Broccoli" cost="2.16" isOrganic="Yes"
isLowFat="Yes"/>
<product name="Vine Ripened Tomatoes" cost="1.69"
isOrganic="No"
isLowFat="Yes"/>
<product name="Yellow Peppers" cost="1.25"
isOrganic="Yes"
isLowFat="Yes"/>
</category>
<category name="Fruit">
<product name="Bananas" cost="0.95" isOrganic="Yes"
isLowFat="Yes"/>
<product name="Grapes" cost="1.34" isOrganic="No"
isLowFat="Yes" />
<product name="Strawberries" cost="2.5" isOrganic="Yes"
isLowFat="Yes"/>
</category>
</catalog>;
// An XMLListCollection representing the data
// for the shopping List.
[Bindable]
public var listDP:XMLListCollection = new XMLListCollection(new
XMLList());
212 Using Data Providers and Collections
// Add the item selected in the Tree to the List XMLList data
provider.
private function doTreeSelect():void
{
if (prodTree.selectedItem)
listDP.addItem(prodTree.selectedItem.copy());
}
// Remove the selected in the List from the XMLList data provider.
private function doListRemove():void
{
if (prodList.selectedItem)
listDP.removeItemAt(prodList.selectedIndex);
}
]]>
</mx:Script>
<mx:Tree id="prodTree" dataProvider="{myData}" width="200"
showRoot="false" labelField="@name"/>
<mx:HBox>
<mx:Button id="treeSelect" label="Add to List"
click="doTreeSelect()"/>
<mx:Button id="listRemove" label="Remove from List"
click="doListRemove()"/>
</mx:HBox>
<mx:List id="prodList" dataProvider="{listDP}" width="200"
labelField="@name"/>
</mx:Application>
Using remote data providers
You can use the following types of remote data providers for Flex components:
■ RPC data sources: HTTPService components, WebService components, and
RemoteObject components
■ Flex DataService components that you use in conjunction with the server-side Flex Data
Management Service to distribute and synchronize data among multiple client
applications.
The following sections describe how you can use these remote data sources to provide data.
For more information on using remote data providers see Chapter 45, “Using RPC
Components,” on page 1407.
Using remote data providers 213
Using an RPC data source
To use an RPC data source, you represent the result of the remote service by using the
appropriate class as follows:
■ The RemoteObject class automatically returns as an ArrayCollection any data that is
represented on the server as a java.util.List object, and you can use the returned object
directly.
■ Otherwise, including for HTTPService and WebService results, convert the return data to
a collection class if the data changes or if you use the same result in multiple places (in the
latter case, you increase efficiency). As a general rule, use an ArrayCollection for serialized
(list-based) objects or an XMLListCollection for data in E4X format.
The following code excerpt shows this use, converting a list returned by a web service to an
ArrayCollection:
<mx:WebService id="employeeWS" destination"employeeWS"
showBusyCursor="true"
fault="alert(event.fault.faultstring)">
<mx:operation name="getList">
<mx:request>
<deptId>{dept.selectedItem.data}</deptId>
</mx:request>
</mx:operation>
.
.
</mx:WebService>
<mx:ArrayCollection id="ac"
source="mx.utils.ArrayUtil.toArray(employeeWS.getList.lastResult)"/>
<mx:DataGrid dataProvider="{ac}" width="100%">
For more information on using RPC data sources, see Chapter 45, “Using RPC
Components,” on page 1407.
Using a DataService component
To use a DataService component as a data provider, you call the component’s fill() method
to fill an ArrayCollection object with the data from a Data Management Service destination,
as the following code excerpt shows:
<mx:Script>
<![CDATA[
import mx.data.DataService;
import mx.collections.ArrayCollection;
public var ds:DataService;
[Bindable]
214 Using Data Providers and Collections
public var contacts:ArrayCollection;
public function initApp()
{
contacts = new ArrayCollection();
ds = new DataService("contact");
ds.fill(contacts);
}
]]>
</mx:Script>
.
.
<mx:DataGrid id="dg" dataProvider="{contacts}" editable="true">
For more information on using DataService components, see Chapter 51, “Distributing Data
in Flex Applications,” on page 1501.
Using paged remote data providers.
When you use a DataService class to get your remote data, you can have a collection that does
not initially load all of its data on the client. By using this technique, you can prevent large
amounts of data from traveling over the network and slowing down your application while
that data is processed. The data that you get incrementally is referred to as paged data, and the
data that has not yet been received is pending data.
About ItemPendingError errors
When you retrieve paged data, your code might try to access pending data. In this case, the
collection throws an ItemPendingError error.
Several Flex controls automatically catch and handle ItemPendingError errors thrown by the
dataProvider collection so that your application does not have to manage the errors. These
controls include: List, HorizontalList, TileList, DataGrid, Menu, and Tree.
Most other classes, including all chart controls, do not handle item pending errors, and you
must write your own error handling code.
You must handle ItemPendingError errors in the following cases:
■ A control that does not handle ItemPendingError errors If the control uses a paged
collection as its data provider, you need to ensure that the data is fully loaded before
passing it to the control, or your application must watch for unexpected behavior from the
control.
Using remote data providers 215
■ You write code that uses a paged collection directly Consider whether your code will
ever attempt to handle pending data. If so, wrap the code that accesses the collection data
in try/catch blocks for the ItemPendingError. For example, if your code iterates through
an entire collection, wrap the while loop in a try/catch block and continue calling until
the iteration is complete.
Handling ItemPendingError errors
All classes that implement the ICollectionView and IList interfaces throw an
ItemPendingError when Flex attempts to access paged collection data that is not yet available.
The ItemPendingError class provides a techniques for finding out about the status of the
requested data as follows:
■ The ItemPendingError object has an addResponder() method that lets you specify an
array of one or more IResponder objects. Flex framework provides an ItemResponder class
that implements the IResponder interface, or you can create your own implementation
class.
■ Each IResponder object must have two functions, a result function that Flex calls when the
data is successfully retrieved and a fault function that Flex calls if the retrieval fails. You
code the functions to handle these circumstances as needed by your application. The
ItemResponder class constructor takes these two functions as parameters, and takes a
third, optional Object parameter that the two functions can use in their processing.
To handle an ItemPendingError:
1. Put the code that might generate the error in a try block.
2. Immediately follow the try block with a catch block with the following signature:
catch (e:ItemPendingError) {
3. Create one or more new responder objects, each with the following format:
responder1 = new ItemResponder(
// The result function
function (data:Object, token:Object=null) {
// Code to handle newly received data goes here.
}
// The fault function
function (info:Object, token:Object=null) {
// Code to handle a failure where data cannot become available
// goes here.
}
// The function must take an optional Object parameter; for
// information see ItemResponder in ActionScript 3.0 Language
Reference.
);
216 Using Data Providers and Collections
4. Add the responder objects to the ItemPendingError object, as follows:
e.addResponder(responder1);
The two functions that you pass in to the Responder constructor define the IResponder
method implementations: the first function defines the implementation of the IResponder
fault method, and the second function defines the implementation of the IResponder
result method. The preceding example uses members of the Flex ItemResponder class as the
responder objects, so it defines methods that take a second, optional parameter.
The following code shows how a function that iterates over a paged collection can handle
ItemPendingError errors:
private var myCursor:IViewCursor;
private var total:int = 0;
// Iterate over the myView collection
private function iterate():void
{
if (myCursor == null)
myCursor = myView.createCursor();
// Put the code that moves the cursor in a try block.
try
{
while(!myCursor.afterLast)
{
total += myCursor.current.amount;
myCursor.moveNext();
}
trace('Total amount is:', total);
}
// The catch block handles the error generated when the requested data
// is pending.
catch (e:ItemPendingError)
{
// Create a new Responder object and assign it to the error object's
// responder property.
responder = new ItemResponder(
// Define a function to handle case where the data becomes available.
function (data:Object, token:Object=null) {
myCursor.moveNext();
iterate();
},
// Define a function to handle case where a "real" error occurs.
function (info:Object, token:Object=null) {
trace('fault when retrieving data', info.toString());
});
}
}
Using remote data providers 217
ItemPendingError notes
Almost all cursor functions may throw ItemPendingErrors. It is worth noting that if an
ItemPendingError is thrown the cursor will remain at its last known good value, meaning that
if you call moveNext() and the error is thrown the cursor will have remained on the old value
of current. A smaller number of methods will throw an error on IList (getItemAt and
getIndexOf primarily), check the ASDoc for details.
Data might not always be loaded sequentially, so it is possible that you will be in the middle of
an ICollectionView and will movePrevious with your cursor and will encounter an
ItemPendingError.
Ensuring all data is available before you display a control
If your application uses a control, such as a chart control, that requires the data provider to
contain the complete data set, your application must ensure that all the data in a collection is
available before assigning the control’s dataProvider property. In most cases, you can do this
by configuring the DataService not to use paging. However, in some cases, such as those
where you use the same Data Management Service destination for multiple purposes in your
Flex application, you might need to use paged data in your control.
One technique for using paged data in a control that requires complete data is to use the IList
interface toArray() method. This method attempts to load all the data in its parameter
object into an Array. If not all the data is available, it throws an ItemPendingError error, and
you can handle the error as described in “Handling ItemPendingError errors” on page 216.
Alternatively, you can iterate from the beginning to the end of the data before using it in the
control.
The following example shows this use to ensure that a paged data provider (specified by the
theDP variable) has complete data before using it in a chart control:
private function loadDP():void
{
var cursor:IViewCursor = theDP.createCursor();
try
{
while (cursor.moveNext()) {}
chart.dataProvider = theDP;
}
catch (e:ItemPendingError)
{
e.addResponder(new ItemResponder(
function (result:Object, token:Object=null)
{
loadDP();
},
218 Using Data Providers and Collections
function (fault:Object, token:Object=null)
{
trace('Error while loading');
}
));
cursor = null; //Might as well let it garbage collect.
}
}
Using remote data providers 219
220 Using Data Providers and Collections
CHAPTER 8
Sizing and Positioning
Components
8
Adobe Flex lays out components by determining their sizes and positions; it provides you with
multiple options for determining both sizes and positions. This topic discusses how Flex lays
out components, and how you can control component size and position.
Contents
About sizing and positioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
Sizing components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .228
Positioning and laying out controls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .248
Using constraint-based layout. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .255
About sizing and positioning
Flex controls the layout of components by using a set of rules. The layout rules are a
combination of sizing rules for individual components, and sizing and positioning rules for
containers. Flex supports automatic layout, so you often do not have to initially set the size or
position of components. Instead, you can concentrate on building the logic of your
application and let Flex control the layout. Later, you can adjust the dimensions of instances,
if necessary.
Each container has its own rules for controlling layout. For example, the VBox container lays
out its children in a single column. A Grid container lays out its children in rows and columns
of cells. The Application container has 24-pixel padding, and many other containers have 0-
pixel padding.
221
Although Flex has built-in default layout rules, you can use the component’s properties and
methods to customize the layout. All components have several properties, including height
and width, for specifying the component’s size in absolute or container-relative terms. Each
container also has properties and styles that you can use to configure aspects of layout. You
can use settings such as the verticalGap and horizontalGap styles of a Tile container to set
the spacing between children, and the direction property to specify a row or column layout.
You can also use different positioning techniques for laying out components in a container;
some containers, for example, support absolute x- and y-coordinate–based positioning.
About layout in Flex
The Layout Manager controls layout in Flex. The manager uses the following three-stage
process to determine the size and position of each component in an application:
1. Commitment pass Determines the property settings of the application’s components.
This phase allows components whose contents depend on property settings to configure
themselves before Flex determines their sizes and positions.
During the commitment pass, the Layout Manager causes each component to run its
commitProperties() method, which determines the property values.
2. Measurement pass Calculates the default size of every component in the application.
This pass starts from the most deeply nested components and works out toward the
Application container. The measurement pass determines the measured, or default, size of
each component. The default size of each container is based on the default or explicit (if
specified) sizes of its children. For example, the Box container’s default width is equal to
the sum of the default or explicit widths of all of its children, plus the thickness of the
borders, plus the padding, plus the gaps between the children.
During the measurement pass, the Layout Manager causes each component to run its
measureSizes() method, which calls the measure() method, to determine the
component’s default size.
3. Layout pass Lays out your application, including moving and resizing any components.
This pass starts from the outermost container and works in toward the innermost
component. The layout pass determines the actual size and placement of each component.
It also does any programmatic drawing, such as calls to the lineTo() or drawRect()
methods.
222 Sizing and Positioning Components
During the layout pass, Flex determines whether any component’s sizing properties specify
dimensions that are a percentage of the parent, and uses the setting to determine the child
component’s actual size. The Layout Manager causes each component to run its
updateDisplayList() method to lay out the component’s children; for this reason, this
pass is also referred to as the update pass.
About Flex frames of reference
Flex uses several frames of reference in determining positions and sizes:
■ The local area and local coordinate system are relative to the outer edges of the
component. The component’s visual elements, such as borders and scroll bars, are
included in the local coordinates.
■ The viewable area is the region of a component that is inside the component’s visual
elements; that is, it is the part of the component that is being displayed and can contain
child controls, text, images, or other contents. Flex does not have a separate coordinate
system for this area.
■ The content area and content coordinate system include all of the component’s contents,
and do not include the visual elements. It includes any regions that are currently clipped
from view and must be accessed by scrolling the component. The content area of a
scrolling TextArea control, for example, includes the region of text that is currently
scrolled off the screen.
Flex uses the viewable area when it determines percentage-based sizes and when it performs
constraint-based layout.
Flex component x and y properties, which you use to specify absolute positioning, are in the
content coordinate system.
Flex coordinates increase from the upper left corner of the frame of reference. Thus, an
N OT E
x,y position of 100,300 in the local coordinate system is 100 pixels is to the right and
300 pixels down from the component’s upper left corner.
For more information on Flex coordinate systems, see “Using Flex coordinates” on page 510.
About component sizing
The measurement and layout passes determine a component’s height and width. You can get
these dimensions by using the height and width properties; you can use these properties and
others to control the component’s size.
Flex provides several ways for you to control the size of controls and containers:
About sizing and positioning 223
Default sizing Flex automatically determines the sizes of controls and containers.
Explicit sizing You set the height and width properties to absolute values.
Percentage-based sizing You specify the component size as a percentage of its container
size.
Constraint-based layout You control size and position by anchoring component’s sides to
locations in their container.
For details on controlling component sizes, see “Sizing components” on page 228.
About component positioning
Flex positions components when your application initializes. Flex also performs a layout pass
and positions or repositions components when the application or a user does something that
could affect the sizes or positions of visual elements, such as the following situations:
■ The application changes properties that specify sizing, such as x, y, width, height,
scaleX, and scaleY.
■ A change affects the calculated width or height of a component, such as when the label
text for a Button control changes, or the user resizes a component.
■ A child is added or removed from a container, a child is resized, or a child is moved. For
example, if your application can change the size of a component, Flex updates the layout
of the container to reposition its children, based on the new size of the child.
■ A property or style that requires measurement and drawing, such as
horizontalScrollPolicy or fontFamily, changes.
There are very few situations where an application programmer must force the layout of a
component; for more information, see “Manually forcing layout” on page 227.
Flex provides two mechanisms for positioning and laying out controls:
Automatic positioning Flex automatically positions a container’s children according to a set
of container- and component-specific rules. Most containers, such as Box, Grid, or Form, use
automatic positioning. Automatic positioning is sometimes referred to as automatic layout.
Absolute positioning You specify each child’s, x and y properties, or use a constraint-based
layout that specifies the distance between one or more of the container’s sides and the child’s
sides or center. Absolute positioning is sometimes referred to as absolute layout.
Three containers support absolute positioning:
■ The Application and Panel containers use automatic positioning by default, and absolute
positioning if you specify the layout property as "absolute".
■ The Canvas container always uses absolute positioning.
224 Sizing and Positioning Components
For details on controlling the positions of controls, see “Positioning and laying out controls”
on page 248.
Component layout patterns
Flex uses different patterns to lay out different containers and their children. These patterns
generally fit in the type categories listed in the following table. The table describes the general
layout behavior for each type, how the default size of the container is determined, and how
Flex sizes percentage-based children.
Container type Default layout behavior
Absolute General layout: Children of the container do not interact. That is,
positioning: Canvas, children can overlap and the position of one child does not affect the
container or position of any other child. You specify the child positions explicitly or
Application or Panel use constraints to anchor the sides or centers of the children relative to
container with the parent container.
layout="absolute" Default sizing: The measurement pass finds the child with the lowest
bottom edge and the child with the rightmost edge, and uses these
values to determine the container size.
Percentage-based children: Sizing uses different rules depending
on whether you use constraint-based layout or x- and y- coordinate
positioning. See “Sizing percentage-based children of a container with
absolute positioning” on page 239.
Controls that General layout: All children of the container are arranged in a single
arrange all children row or column. Each child’s height and width can differ from all other
linearly, such as children’s heights or widths.
Box, HBox, VBox Default sizing: The container fits the default or explicit sizes of all
children and all gaps, borders, and padding.
Percentage based children: If children with percentage-based
sizing request more than the available space, the actual sizes are set to
fit in the space, proportionate to the requested percentages.
About sizing and positioning 225
Container type Default layout behavior
Grid General layout: The container is effectively a VBox control with rows
of HBox child controls, where all items are constrained to align with
each other. The heights of all the cells in a single row are the same, but
each row can have a different height. The widths of all cells in a single
column are the same, but each column can have a different width. You
can define a different number of cells for each row or each column of
the Grid container, and individual cells can span columns or rows.
Default sizing: The grid fits the individual rows and children at their
default sizes.
Percentage-based children: If children use percentage-based
sizing, the sizing rules fit the children GridItem components within their
rows, and GridRow components within the grid size according to linear
container sizing rules.
Tile General layout: The container is a grid of equal-sized cells. The cells
can be in row-first or column-first order.
If you do not specify explicit or percentage-based dimensions, the
control has as close as possible to an equal number of rows and
columns, with the direction property determining the orientation with
the larger number of items, if necessary.
Default sizing: If you do not specify tileWidth and tileHeight
properties, the container uses the measured or explicit size of the
largest child cell for the size of each child cell.
Percentage based children: The percentage-based sizes of a child
component specify a percentage of the individual cell, not of the Tile
container.
Navigators: General layout: The container displays one child at a time.
ViewStack, Default sizing: The container size is determined by the measured or
Accordion, explicit dimensions of the initially selected child, and thereafter, all
TabNavigator children are forced to be that initial size. If you set the resizeToChild
property to true the container resizes to accommodate the measured
or explicit size of each child, as that child appears.
Percentage based children: As a general rule, you either use 100%
for both height and width, which causes the children to fill the navigator
bounds, or do not use percentage-based sizing.
Basic layout rules and considerations
Flex performs layout according to the following basic rules. If you remember these rules, you
should be able to easily understand the details of Flex layout. These rules should help you
determine why Flex lays out your application as it does and to determine how to modify your
application appearance.
226 Sizing and Positioning Components
For a detailed description of how Flex sizes components, see “Determining and controlling
component sizes” on page 231. For detailed information on component positioning, see
“Positioning and laying out controls” on page 248.
■ Flex first determines all components’ measured (default) or explicitly-set sizes up, from the
innermost child controls to the outermost (Application) control. This is done in the
measurement pass.
■ After the measurement pass, Flex determines all percentage-based sizes and lays out
components down, from the outermost container to the innermost controls. This is done
in the layout pass.
■ Sizes that you set to a pixel value are mandatory and fixed, and override any maximum or
minimum size specifications that you set for the component.
■ The default sizes determined in the measurement pass specify the sizes of components that
do not have explicit or percentage-based sizes (or use constraint-based layout), and are
fixed.
■ Percentage-based size specifications are advisory. The layout algorithms satisfy the request
if possible, and use the percentage values to determine proportional sizes, but the actual
sizes can be less than the requested sizes. Percentage-based sizes are always within the
component’s maximum and minimum sizes, and, subject to those bounds, don’t cause a
container’s children to exceed the container size.
Manually forcing layout
Sometimes, you must programmatically cause Flex to lay out components again. Flex
normally delays processing properties that require substantial computation until the script
that causes them to be set finishes executing. For example, setting the width property is
delayed, because it may require recalculating the widths of the object’s children or its parent.
Delaying processing prevents it from being repeated multiple times if the script sets the
object’s width property more than once. However, in some situations, you might have to force
the layout before the script completes.
Situations where you must force a layout include the following circumstances:
■ When printing multiple page data grids by using the PrintDataGrid class.
■ Before playing an effect, if the start values have just been set on the target.
■ When capturing bitmap data after making property changes.
To force a layout, call the validateNow() method of the component that needs to be laid
out. This method causes Flex to validate and update the properties, sizes, and layout of the
object and all its children, and to redraw them, if necessary. Because this method is
computation-intensive, you should be careful to call it only when it is necessary.
About sizing and positioning 227
For an example of using the validateNow() method, see “Updating the PrintDataGrid
layout” on page 1174.
Sizing components
Flex provides several ways for controlling the size of components. You can do the following:
■ Have Flex automatically determine and use default component sizes.
■ Specify pixel sizes.
■ Specify component size as a percentage of the parent container.
■ Combine layout and sizing by specifying a constraint-based layout.
The following sections describe the basic sizing properties, provide details on how Flex
determines component sizes, describe how to use automatic, explicit, and percentage-based
sizing, and describe various techniques for controlling component size. For information on
constraint-based layout, see “Using constraint-based layout” on page 255.
Flex sizing properties
Several Flex properties affect the size of components. As a general rule, you use only a few
properties for most applications, but a more complete understanding of these properties can
help you understand the underlying Flex sizing mechanism and how Flex sizing properties
interrelate. For more information on Flex component sizes, see “Determining and controlling
component sizes” on page 231.
The following sections describe the most commonly used sizing properties, followed by tables
that describe all characteristics and properties that determine how Flex sizes components. The
tables include properties that are not normally used by many application developers; these
properties can be used by developers of custom components, particularly, those who must
implement a custom measure() method. The last subsection describes specific sizing
behaviors and techniques that can be useful in developing applications.
228 Sizing and Positioning Components
Commonly used sizing properties
If you are not creating custom components, you typically use the following basic properties to
specify how a component is sized:
■ The height, width, percentHeight, and percentWidth properties specify the height
and width of a component. In MXML tags, you use the height and width properties to
specify the dimensions in pixels or as percentages of the parent container size. In
ActionScript, you use the height and width properties to specify the dimensions in
pixels, and use the percentHeight and percentWidth properties to specify the
dimensions as a percentage of the parent container.
■ The minHeight, minWidth, maxHeight, and maxWidth properties specify the minimum
and maximum dimensions that a component can have if Flex determines the component
size. These properties have no effect if you explicitly set the width or height in pixels.
The following sections describe these properties in greater detail and explain how they relate
to each other. Flex provides a number of powerful and subtle sizing features, and
understanding these concepts can help you, even if you never use any properties other than
the ones listed in this section. The section “Determining and controlling component sizes”
on page 231 describes the rules that Flex applies to determine the sizes of components based
on the properties.
Basic sizing characteristics and properties
The following characteristics and their associated properties determine the size of the
component:
Characteristic Associated Description
properties
Actual Returned by the height The height and width of the displayed control,
dimensions and width properties. in pixels, as determined by the layout phase.
If you set any explicit values, they determine
the corresponding actual values.
Explicit explicitHeight, A dimension that you specifically set as a
dimensions explicitWidth number of pixels. These dimensions cannot be
Setting the height and overridden.
width properties to Application developers typically use the height
integer values also sets and width properties to set explicit dimensions.
the explicitHeight and You cannot have both an explicit dimension
explicitWidth properties. and a percentage-based dimension, setting
one unsets the other.
Sizing components 229
Characteristic Associated Description
properties
Percentage- percentHeight, A dimension that you specifically set as a
based percentWidth number in the range 0-100, as a percentage of
dimensions In MXML tags only, the viewable area of the parent container.
setting the height and If you set a percentage-based dimension, the
width properties to component is resizable, and grows or shrinks if
percentage string values, the parent dimension changes.
such as “50%” also sets
the percentHeight and
percentWidth properties.
Default measuredHeight, Not used directly by application developers.
dimensions measuredWidth The dimensions of the component, as
determined by the measure() method of the
component.
These values cannot be outside the range
determined by the component’s maximum and
minimum height and width values. For more
information on maximum and minimum default
sizes, see “Maximum and minimum
dimensions”.
Maximum and minimum dimensions
The following characteristics determine the minimum and maximum default and percentage-
based dimensions that a component can have. They do not affect values that you set explicitly
or dimensions determined by using constraint-based layout.
Characteristic Associated Description
Properties
Minimum minHeight, minWidth The minimum dimensions a component can
dimensions Setting the explicit have.
minimum dimensions also By default, Flex sets these dimensions to the
sets the. minHeight and values of the minimum default dimensions.
minWidth properties.
230 Sizing and Positioning Components
Characteristic Associated Description
Properties
Maximum maxHeight, maxWidth The maximum dimensions a component can
dimensions Setting the explicit have.
maximum dimensions The default values of these properties are
also sets the maxHeight component-specific, but often are 10000
and maxWidth properties. pixels.
Minimum default measuredMinHeight, Not used by application developers.
dimensions measuredMinWidth The minimum valid dimensions, as determined
by the measure() method. The default values
for these properties are component-specific;
for many controls, the default values are 0.
Determining and controlling component sizes
The following sections describe in detail how Flex determines the sizes of controls and
containers based on the components and their properties and how you can use Flex properties
to control the sizes. The first section describes how you can use different sizing properties to
control component size. The second section describes general sizing rules that apply to both
controls and containers. The third section describes rules for sizing containers.
For a summary of the basic rules for component sizing, see “Basic layout rules and
N OT E
considerations” on page 226.
Basic sizing property rules
The following rules describe how you can use Flex sizing properties to specify the size of a
component:
■ Any dimension property that you set overrides the corresponding default value; for
example, an explicitly set height property overrides any default height.
■ Setting the width, height, maxWidth, maxHeight, minWidth, or minHeight property to
a pixel value in MXML or ActionScript also sets the corresponding explicit property, such
as explicitHeight or explicitMinHeight.
■ The explicit height and width and the percentage-based height and width are mutually
exclusive. Setting one value sets the other to NaN; for example, if you set height or
explicitHeight to 50 and then set percentHeight to 33, the value of the
explicitHeight property is NaN, not 50, and the height property returns a value that is
determined by the percentHeight setting.
Sizing components 231
■ If you set the height or width property to a percentage value in an MXML tag, you
actually set the percentage-based value, that is, the percentHeight or percentWidth
property, not the explicit value. In ActionScript, you cannot set the height or width
property to a percentage value; instead, you must set the percentHeight or
percentWidth property.
■ When you get the height and width properties, the value is always the actual height or
width of the control.
Determining component size
During the measurement pass, Flex determines the components’ default, (also called
measured) sizes. During the layout pass, Flex determines the actual sizes of the components,
based on the explicit or default sizes and any percentage-based size specifications.
The following list describes sizing rules and behaviors that apply to all components, including
both controls and containers. For container-specific sizing rules, see “Determining container
size” on page 233. For detailed information on percentage-based sizing, see “Using
percentage-based sizing” on page 237.
■ If you specify an explicit size for any component (that is not outside the component’s
minimum or maximum bounds), Flex always uses that size.
■ If you specify a percentage-based size for any component, Flex determines the
component’s actual size as part of the parent container’s sizing procedure, based on the
parent’s size, the component’s requested percentage, and the container-specific sizing and
layout rules.
■ The default and percentage-based sizes are always at least as large as any minimum size
specifications.
■ If you specify a component size by using a percentage value and do not specify an explicit
or percentage-based size for its container, the component size is the default size. Flex
ignores the percentage specification. (Otherwise, an infinite recursion might result.)
■ If a child or set of children require more space than is available in the parent container, the
parent clips the children at the parent’s boundaries, and, by default, displays scroll bars on
the container so users can scroll to the clipped content. Set the clipContent property to
false to configure a parent to let the child extend past the parent’s boundaries. Use the
scrollPolicy property to control the display of the scroll bars.
■ If you specify a percentage-based size for a component Flex uses the viewable area of the
container in determining the sizes.
232 Sizing and Positioning Components
■ When sizing and positioning components, Flex does not distinguish between visible and
invisible components. By default, an invisible component is sized and positioned as if it
were visible. To prevent Flex from considering an invisible component when it sizes and
positions other components, set the component’s includeInLayout property to false.
This property affects the layout of the children of all containers except Accordion,
FormItem, or ViewStack. For information on using the “Preventing layout of hidden
controls” on page 251.
Setting a component’s includeInLayout property to false does not prevent Flex from
NO TE
laying out or displaying the component; it only prevents Flex from considering the
component when it lays out other components. As a result, the next component or
components in the display list overlap the component. To prevent Flex from
displaying the component, also set the visible property to false.
Determining container size
Flex uses the following basic rules, in addition to the basic component sizing rules, to
determine the size of a container:
■ Flex determines all components’ default dimensions during the measurement pass, and
uses these values when it calculates container size during the layout pass.
■ If you specify an explicit size for a container, Flex always uses that size, as with any
component.
■ If you specify a percentage-based size for a container, Flex determines the container’s
actual size as part of the parent container’s sizing procedure, as with any component.
■ A percentage-based container size is advisory. Flex makes the container large enough to fit
its children at their minimum sizes. For more information on percentage-based sizing, see
“Using percentage-based sizing” on page 237.
■ If you do not specify an explicit or percentage-based size for a container, Flex determines
the container size by using explicit sizes that you specify for any of its children, and the
default sizes for all other children.
■ Flex does not consider any percentage-based settings of a container’s children when sizing
the container; instead, it uses the child’s default size.
■ If a container uses automatic scroll bars, Flex does not consider the size of the scroll bars
when it determines the container’s default size in its measurement pass. Thus, if a scroll
bar is required, a default-sized container might be too small for proper appearance.
Sizing components 233
Each container has a set of rules that determines the container’s default size. For information
on default sizes of each control and container, see the specific container sections in Adobe
Flex 2 Language Reference, and in the following topics in Flex 2 Developer’s Guide: Chapter 14,
“Using the Application Container,” on page 529; Chapter 15, “Using Layout Containers,” on
page 553; and Chapter 16, “Using Navigator Containers,” on page 627.
Example: Determining an HBox container and child sizes
The following example code shows how Flex determines the sizes of an HBox container and
its children. In this example, the width of the HBox container is the sum of the default width
of the first and third buttons, the minimum width of the second button (because the default
width would be smaller), and 16 for the two gaps. The default width for buttons is based on
the label text width; in this example it is 66 pixels for all three buttons. The HBox width,
therefore, is 66 + 70 + 66 + 16 = 218. If you change the minWidth property of the second
button to 50, the calculation uses the button’s default width, 66, so the HBox width is 214.
When Flex lays out the application, it sets the first and third button widths to the default
values, 66, and the second button size to the minimum width, 70. It ignores the percentage-
based specifications when calculating the final layout.
<?xml version="1.0"?>
<!-- components\HBoxSize.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox id="h21">
<mx:Button id="bG1"
label="Label 1"
width="50%"/>
<mx:Button id="bG2"
label="Label 2"
width="40%"
minWidth="70"/>
<mx:Button id="bG3"
label="Label 3"/>
</mx:HBox>
<mx:TextArea height="50" width="100%">
<mx:text>
HBox: {h21.width} Button1: {bG1.width} Button2: {bG2.width}
Button3: {bG3.width}
</mx:text>
</mx:TextArea>
</mx:Application>
234 Sizing and Positioning Components
In the following example, the HBox width now is 276 pixels, 50% of 552 pixels, where 552 is
the Application container width of 600 minus 48 pixels for the 24-pixel left and right
container padding. The button sizes are 106, 85, and 66 pixels respectively. The third button
uses the default size. The variable width button sizes are five-ninths and four-ninths of the
remaining available space after deducting the default-width button and the gaps, and the 1-
pixel-wide border.
If you set the HBox width property to 20%, however, the HBox width is not 120 pixels, 20%
of the Application container width, because the this value is too small to fit the HBox
container’s children. Instead it is 200, the sum of 66 pixels (the default size) for buttons 1 and
3, 50 pixels (the specified minimum size) for button 2, 16 pixels for the gaps between buttons,
and 2 pixels for the border. The buttons are 66, 50, and 66 pixels wide, respectively.
<?xml version="1.0"?>
<!-- components\HBoxSizePercent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox id="h21" width="50%" borderStyle="solid">
<mx:Button id="bG1"
label="Label 1"
width="50%"/>
<mx:Button id="bG2"
label="Label 2"
width="40%"
minWidth="50"/>
<mx:Button id="bG3"
label="Label 3"/>
</mx:HBox>
<mx:TextArea height="50" width="100%">
<mx:text>
HBox: {h21.width} Button1: {bG1.width} Button2: {bG2.width}
Button3: {bG3.width}
</mx:text>
</mx:TextArea>
</mx:Application>
For more information and examples showing sizing of containers and children, see “Using
Flex component sizing techniques” on page 236. For detailed information on percentage-
based sizing, see “Using percentage-based sizing” on page 237.
Sizing components 235
Using Flex component sizing techniques
The following sections describe briefly how you can use default sizing, explicit sizing, and
percentage-based sizing techniques to control the size of components. For information on
using constraint-based layout for component sizing, see “Using constraint-based layout”
on page 255.
Using default sizing
If you do not otherwise specify sizes, the component’s measure() method calculates a size
based on the default sizing characteristics of the particular component and the default or
explicit sizes of the component’s child controls.
As a general rule, you should determine whether a component’s default size (as listed for the
component in Flex 2 Developer’s Guide) is appropriate for your application. If it is, you do not
have to specify an explicit or percentage-based size.
The following example shows how you can use default sizing for Button children of an HBox
container. In this example, none of the children of the HBox container specify a width value:
<?xml version="1.0"?>
<!-- components\DefaultButtonSize.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox width="400" borderStyle="solid">
<mx:Button label="Label 1"/>
<mx:Button label="Label 2"/>
<mx:Button label="Label 3"/>
</mx:HBox>
</mx:Application>
Flex, therefore, uses the default sizes of the buttons, which accommodate the button label and
default padding, and draws this application as the following image shows:
Notice the empty space to the right of the third button, because the sum of the default sizes is
less than the available space.
236 Sizing and Positioning Components
Specifying an explicit size
You use the width and height properties of a component to explicitly set its size, as follows:
<?xml version="1.0"?>
<!-- components\ExplicitTextSize.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox id="myHBox">
<mx:TextInput id="myInput"
width="200"
height="40"/>
</mx:HBox>
</mx:Application>
In this example, Flex sets the component sizes to 200 by 40 pixels.
The following example shows setting the sizes of a container and its child:
<?xml version="1.0"?>
<!-- components\ExplicitHBoxSize.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox id="myHBox" width="150" height="150">
<mx:TextInput id="myInput"
text="Enter the zip code"
width="200"
height="40"/>
</mx:HBox>
</mx:Application>
Because the specified TextInput control size is larger than that of its parent HBox container,
Flex clips the TextInput control at the container boundary and displays a scroll bar (if you do
not disable it) so that you can scroll the container to the clipped content. For more
information on scroll bar sizing considerations, see “Dealing with components that exceed
their container size” on page 243.
Using percentage-based sizing
Percentage-based sizing dynamically determines and maintains a component’s size relative to
its container; for example, you can specify that the component’s width is 75% of the
container. This sizing technique has several advantages over default or explicit fixed sizing:
■ You only have to specify a size relative to the container; you don’t have to determine exact
measurements.
■ The component size changes dynamically when the container size changes.
■ The sizing mechanism automatically takes into account the remaining available space and
fits components even if their requested size exceeds the space.
Sizing components 237
To specify a percentage value, use one of the following coding techniques:
■ In an MXML tag, set the height or width property to a percentage value; for example:
<mx:TextArea id="ta1" width="70%" height="40%"/>
■ In an MXML tag or an ActionScript statement, set the percentHeight or percentWidth
property to a numeric value; for example:
ta1.percentWidth=70;
The exact techniques Flex uses to determine the dimensions of a component that uses
percentage-based sizing depend on the type of container that holds the container. For
example, a Tile container has cells that are all the largest default or explicit dimensions of the
largest child. Child control percentage values specify a percentage of the tile cell size, not of
the Tile control size. The percentage sizes of the Box, HBox, and VBox containers, on the
other hand, are relative to the container size.
Sizing percentage-based children of a linear container with automatic
positioning
When Flex sizes children of a container that uses automatic positioning to lay out children in
a single direction, such as a HBox or VBox container, Flex does the following:
1. Determines the size of the viewable area of the parent container, and uses the
corresponding dimensions as the container dimensions for sizing calculations. The
viewable area is the part of the component that is being displayed and can contain child
controls, text, images, or other contents. For more information on calculating the size of
containers, see “Determining component size” on page 232.
2. Determines the desired sizes of children with percentage-based sizes by multiplying the
decimal value by the size of the viewable area of the container, minus any padding and
inter-child gaps.
3. Reserves space for all children with explicit or default sizes.
4. If available space (parent container size minus all reserved space, including borders,
padding, and gaps) cannot accommodate the percentage requests, divides the available
space in proportion to the specified percentages.
5. If a minimum or maximum height or width specification conflicts with a calculated value,
uses the minimum or maximum value, and recalculates all other percentage-based
components based on the reduced available space.
6. Rounds the size down to the next integer.
238 Sizing and Positioning Components
The following examples show how the requested percentage can differ from the size when the
component is laid out:
■ Suppose that 50% of a HBox parent is available after reserving space for all explicit-sized
and default-sized components, and for all gaps and padding. If one component requests
20% of the parent, and another component requests 60%, the first component is sized to
12.5% ((20 / 20+ 60) * 50%) of the parent container, the second component is sized to
37.5% of the parent container.
■ If any component, for example, a Tile container, requests 100% of its parent Application
container’s space, it occupies all of the container except for the Application’s 24-pixel-wide
top, bottom, left, and right padding, unless you explicitly change the padding settings of
the Application container.
Sizing percentage-based children of a container with absolute positioning
When Flex sizes children of a container that uses absolute positioning, it does the following:
1. Determines the viewable area of the parent container, and uses the corresponding
dimensions as the container dimensions for sizing calculations. For more information on
calculating the size of containers, see “Determining component size” on page 232.
2. Determines the sizes of children with percentage-based sizes by multiplying the decimal
value by the container dimension minus the position of the control in the dimension’s
direction. For example, if you specify x="10" and width="100%" for a child, the child size
extends only to the edge of the viewable area, not beyond.
Because controls can overlay other controls or padding, the sizing calculations do not
consider padding or any other children when determining the size of a child.
3. If a minimum or maximum height or width specification conflicts with a calculated value,
uses the minimum or maximum value.
4. Rounds the size down to the next integer.
Sizing components 239
The following code shows the percentage-based sizing behavior with absolute positioning:
<?xml version="1.0"?>
<!-- components\PercentSizeAbsPosit.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
backgroundGradientColors="[#FFFFFF, #FFFFFF]"
verticalGap="25">
<mx:Canvas
width="200" height="75"
borderStyle="solid">
<mx:HBox
x="20" y="10"
width="100%" height="25"
backgroundColor="#666666"/>
</mx:Canvas>
<mx:Canvas
width="200" height="75"
borderStyle="solid">
<mx:HBox
left="20" top="10"
width="100%" height="25"
backgroundColor="#666666"/>
</mx:Canvas>
</mx:Application>
Flex draws the following application:
240 Sizing and Positioning Components
Examples: Using percentage-based children of an HBox container
The following example specifies percentage-based sizes for the first two of three buttons in an
HBox container:
<?xml version="1.0"?>
<!-- components\PercentHBoxChildren.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox width="400">
<mx:Button label="Label 1" width="25%"/>
<mx:Button label="Label 2" width="40%"/>
<mx:Button label="Label 3"/>
</mx:HBox>
</mx:Application>
In this example, the default width of the third button is 66 pixels. The HBox container has no
padding by default, but it does put a 8-pixel horizontal gap between each component. Because
this application has three components, these gaps use 16 pixels, so the available space is 384.
The first button requests 25% of the available space, or 96 pixels. The second button requests
40% of 384 pixels, rounded down to 153 pixels. There is still unused space to the right of the
third button.
Flex draws the following application:
Now change the percentage values requested to 50% and 40%, respectively:
<?xml version="1.0"?>
<!-- components\PercentHBoxChildren5040.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox width="400">
<mx:Button label="Label 1"
width="50%"/>
<mx:Button label="Label 2"
width="40%"/>
<mx:Button label="Label 3"/>
</mx:HBox>
</mx:Application>
In this example, the first button requests 50% of the available HBox space, or 192 pixels. The
second button still requests 40%, or 153 pixels, for a total of 345 pixels. However, the HBox
only has 318 pixels free after reserving 66 pixels for the default-width button and 16 pixels for
the gaps between components. Flex divides the available space proportionally between the two
buttons, giving .5/(.5 + .4) * 318 = 176 pixels, to the first button and .4/(.5 + .4) * 318 = 141
pixels, to the second button. (All calculated values are rounded down to the nearest pixel.)
Sizing components 241
Flex draws the following application:
Using minimum or maximum dimensions
You can also use the minWidth, minHeight, maxWidth, and maxHeight properties with a
percentage-based component to constrain its size. Consider the following example:
<?xml version="1.0"?>
<!-- components\PercentHBoxChildrenMin.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox width="400">
<mx:Button label="Label 1"
width="50%"/>
<mx:Button label="Label 2"
width="40%"
minWidth="150"/>
<mx:Button label="Label 3"/>
</mx:HBox>
</mx:Application>
To determine the widths of the percentage-based button sizes, Flex first determines the sizes as
described in the second example in “Examples: Using percentage-based children of an HBox
container” on page 241, which results in requested values of 176 for the first button and 141
for the second button. However, the minimum width of the second button is 150, so Flex sets
its size to 150 pixels, and reduces the size of the first button to occupy the remaining available
space, which results in a width of 168 pixels.
Flex draws the following application:
Sizing containers and components toolbox
The following sections describe specific techniques for controlling sizing, including setting the
Application container size, handling components that exceed the container size, and using
padding and custom gaps.
Setting the Application container size
When you size an application, you often start by setting the size of the Application container.
The Application container determines the boundaries of your application in the Adobe Flash
Player 9.
242 Sizing and Positioning Components
If you are using Flex Builder, or are compiling your MXML application on the server, an
HTML wrapper page is generated automatically. The width and height properties specified
in the <mx:Application> tag are used to set the width and height of the <object> and
<embed> tags in the HTML wrapper page. Those numbers determine the portion of the
HTML page that is allocated to the Flash plug-in.
If you are not autogenerating the HTML wrapper, set the <mx:Application> tag’s width and
height properties to 100%. That way, the Flex application scales to fit the space that is
allocated to the Flash plug-in.
You set the Application container size by using the <mx:Application> tag, as the following
example shows:
<?xml version="1.0"?>
<!-- components\AppExplicit.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
height="100"
width="150">
<!-- Application children go here. -->
</mx:Application>
In this example, you set the Application container size to 100 by 150 pixels. Anything in the
application larger than this window is clipped at the window boundaries. Therefore, if you
define a 200 pixel by 200 pixel DataGrid control, it is clipped, and the Application container
displays scroll bars. (You can disable, or always display, scroll bars by setting the container’s
horizontalScrollPolicy and verticalScrollPolicy properties.)
For more information on sizing the Application container, see Chapter 14, “Using the
Application Container,” on page 529.
Dealing with components that exceed their container size
If the sum of the actual sizes of a container’s children, plus the gaps and padding, exceed the
dimensions of the container, by default, the container’s contents are clipped at the container
boundaries, and Flex displays scroll bars on the container so you can scroll to the remaining
content. If you set the horizontalScrollPolicy and verticalScrollPolicy properties to
ScrollPolicy.OFF, the scroll bars do not appear, but users do not have access to the clipped
contents. If you set the clipContent property to false, container content can extend
beyond the container boundary.
Sizing components 243
Using Scroll bars
If Flex cannot fit all of the components into the container, it uses scroll bars, unless you
disable them by setting the horizontalScrollPolicy or verticalScrollPolicy property
to ScrollPolicy.OFF or by setting clipContent to false. Consider the following example:
<?xml version="1.0"?>
<!-- components\ScrollHBox.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox width="400">
<mx:Button label="Label 1"
width="50%"
minWidth="200"/>
<mx:Button label="Label 2"
width="40%"
minWidth="150"/>
<mx:Button label="Label 3"/>
</mx:HBox>
</mx:Application>
In this example, the default width of the fixed-size button is 66 pixels, so there are 324 pixels
of space available for the percentage-based buttons after accounting for the gap between
components. The minimum widths of the first and second buttons are greater than the
percentage-based values, so Flex assigns those buttons the set widths of 200 and 150 pixels,
even though the HBox container only had 324 pixels free. The HBox container uses scroll
bars to provide access to its contents because they now consume more space than the
container itself.
244 Sizing and Positioning Components
Notice that the addition of the scroll bar doesn’t increase the height of the container from its
initial value. Flex considers scroll bars in its sizing calculations only if you explicitly set the
scroll policy to ScrollPolicy.ON. So, if you use an auto scroll policy (the default), the scroll
bar overlaps the buttons. To prevent this behavior, you can set the height property for the
HBox container or allow the HBox container to resize by setting a percentage-based width.
Remember that changing the height of the HBox container causes other components in your
application to move and resize according to their own sizing rules. The following example
adds an explicit height and permits you to see the buttons and the scroll bar:
<?xml version="1.0"?>
<!-- components\ScrollHBoxExplicitHeight.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox width="400" height="42">
<mx:Button label="Label 1"
width="50%"
minWidth="200"/>
<mx:Button label="Label 2"
width="40%"
minWidth="150"/>
<mx:Button label="Label 3"/>
</mx:HBox>
</mx:Application>
Alternately, you can set the HBox control’s horizontalScrollPolicy property to
ScrollPolicy.ON. This reserves space for the scroll bar during the initial layout pass, so it fits
without overlapping the buttons or setting an explicit height. This also correctly handles the
situation where the scroll bars change their size when you change skinning or styles. This
technique places an empty scroll bar area on the container if it does not need scrolling,
however.
Sizing components 245
Using the clipContent property
If you set the clipContent property for the parent container to false, the content can
extend beyond the container’s boundaries and no scroll bars appear, as the following example
shows:
<?xml version="1.0"?>
<!-- components\ClipHBox.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
width="600"
height="400"
backgroundGradientColors="[#FFFFFF, #FFFFFF]">
<mx:HBox id="myHBox"
width="150"
height="150"
borderStyle="solid"
backgroundColor="#996666"
clipContent="false">
<mx:TextInput id="myInput"
width="200" height="40"
backgroundColor="#99FF99"/>
</mx:HBox>
</mx:Application>
The following image shows the application, with the TextInput control extending past the
right edge of the HBox control:
To ensure that components fit in the container, reduce the sizes of the child components. You
can do this by setting explicit sizes that fit in the container, or by specifying percentage-based
sizes. If you set percentage-based sizes, Flex shrinks the children to fit the space, or their
minimum sizes, whichever is larger. By default, Flex sets the minimum height and width of
most components to 0. You can set these components’ minimum properties to nonzero values
to ensure that they remain readable.
246 Sizing and Positioning Components
Using padding and custom gaps
There may be situations where you want your containers to have padding around the edges.
(Previous Flex releases used the term margins; Flex 2 uses the term padding for consistency
with cascading style sheet conventions.) Some containers, such as the Application container,
have padding by default; others, such as the HBox container, have padding values of 0 by
default. Also, some containers have gaps between children, which you might want to change
from the default values. If your application has nonzero padding and gaps, Flex reserves the
necessary pixels before it sizes any percentage-based components. Consider the following
example:
<?xml version="1.0"?>
<!-- components\PadHBox.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox
width="400"
borderStyle="solid"
paddingLeft="5"
paddingRight="5"
horizontalGap="5">
<mx:Button label="Label 1"
width="50%"/>
<mx:Button label="Label 2"
width="40%"
minWidth="150"/>
<mx:Button label="Label 3"/>
</mx:HBox>
</mx:Application>
The default width of the fixed-size button is 66 pixels. All horizontal padding and gaps in the
HBox control are 5 pixels wide, so the Flex application reserves 5 pixels for the left padding, 5
pixels for the right padding, and 10 pixels total for the two gaps between components, which
leaves 314 pixels free for the two percentage-based components. Flex reserves 66 pixels for the
default-sized (third) button; the second button requires its minimum size, 150 pixels; and the
padding and gap take 20 pixels; this leaves 164 pixels available for the first button. The first
button requests 200 pixels; therefore, it uses all available pixels and is 164 pixels wide.
Flex draws the following application:
Sizing components 247
Positioning and laying out controls
By default, Flex automatically positions all components, except for the children of a Canvas
container. If you have a Canvas container, or an Application or Panel container with the
layout property set to absolute, you specify absolute positions for its children, or use
constraint-based layout. The following sections describe how to use automatic positions and
absolute positioning by using x and y properties. For information on using constraint-based
layout, which can control both positioning and sizing, see “Using constraint-based layout”
on page 255.
Using automatic positioning
For most containers, Flex automatically positions the container children according to the
container’s layout rules, such as the layout direction, the container padding, and the gaps
between children of that container.
For containers that use automatic positioning, setting the x or y property directly or calling
move() has no effect, or only a temporary effect, because the layout calculations set the x
position to the calculation result, not the specified value. You can, however, specify absolute
positions for the children of these containers under some circumstances; for more
information, see “Disabling automatic positioning temporarily” on page 249.
You can control aspects of the layout by specifying container properties; for details on the
properties, see the property descriptions for the container in Adobe Flex 2 Language Reference.
You also control the layout by controlling component sizes and by using techniques such as
adding spacers.
The following sections describe specific techniques for controlling automatic positioning:
■ Using the Spacer control to control layout
■ Disabling automatic positioning temporarily
■ Preventing layout of hidden controls
Using the Spacer control to control layout
Flex includes a Spacer control that helps you lay out children within a parent container. The
Spacer control is invisible, but it does allocate space within its parent.
248 Sizing and Positioning Components
In the following example, you use a percentage-based Spacer control to push the Button
control to the right so that it is aligned with the right edge of the HBox container:
<?xml version="1.0"?>
<!-- components\SpacerHBox.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox width="400">
<mx:Image source="assets/flexlogo.jpg"/>
<mx:Label text="Company XYZ"/>
<mx:Spacer width="100%"/>
<mx:Button label="Close"/>
</mx:HBox>
</mx:Application>
In this example, the Spacer control is the only percentage-based component in the HBox
container. Flex sizes the Spacer control to occupy all available space in the HBox container
that is not required for other components. By expanding the Spacer control, Flex pushes the
Button control to the right edge of the container.
You can use all sizing and positioning properties with the Spacer control, such as width,
height, maxWidth, maxHeight, minWidth, and minHeight.
Disabling automatic positioning temporarily
You can use effects, such as the Move and Zoom effects, to modify the size or position of a
child in response to a user action. For example, you might define a child so that when the user
selects it, the child moves to the top of the container and doubles in size. These effects modify
the x and y properties of the child as part of the effect. Similarly, you might want to change
the position of a control by changing its x or y coordinate value, for example, in response to a
button click.
Containers that use automatic positioning ignore the values of the x and y properties of their
children during a layout update. Therefore, the layout update cancels any modifications to the
x and y properties performed by the effect, and the child does not remain in its new location.
You can prevent Flex from performing automatic positioning updates that conflict with the
requested action of your application by setting the autoLayout property of a container to
false. Setting this property to false prevents Flex from laying out the container’s contents
when a child moves or resizes. Flex defines the autoLayout property in the Container class,
and all containers inherit it; its default value is true, which enables Flex to update layouts.
Positioning and laying out controls 249
Even when you set the autoLayout property of a container to false, Flex updates the layout
when you add or remove a child. Application initialization, deferred instantiation, and the
<mx:Repeater> tag add or remove children, so layout updates always occur during these
processes, regardless of the value of the autoLayout property. Therefore, during container
initialization, Flex defines the initial layout of the container children regardless of the value of
the autoLayout property.
The following example disables layout updates for a VBox container:
<?xml version="1.0"?>
<!-- components\DisableVBoxLayout.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:VBox autoLayout="false"
width="200"
height="200">
<mx:Button/>
<mx:Button id="btn"
click="btn.x += 10;"/>
<mx:Button id="btn2"
creationComplete="btn2.x = 100; btn2.y = 75;"/>
</mx:VBox>
</mx:Application>
In this example, Flex initially lays out all three Button controls according to the rules of the
VBox container. The creationComplete event listener for the third button is dispatched after
the VBox control has laid out its children, but before Flex displays the buttons. Therefore,
when the third button appears, it is at the x and y positions specified by the creationComplete
listener. After the buttons appear, Flex shifts the second button 10 pixels to the right each
time a user clicks it.
Setting the autoLayout property of a container to false prohibits Flex from updating a
container’s layout after a child moves or resizes, so you should set it to false only when
absolutely necessary. You should always test your application with the autoLayout property
set to the default value of true, and set it to false only as necessary for the specific container
and specific actions of the children in that container.
For more information on effects, see Chapter 17, “Using Behaviors,” on page 649.
250 Sizing and Positioning Components
Preventing layout of hidden controls
By default, Flex lays out and reserves space for all components, including hidden components,
but it does not display the hidden controls. You see blank spots where the hidden controls will
appear when you make them visible. In place of the hidden controls, you see their container’s
background. However if the container is any of the following components, you can prevent
Flex from considering the child component when it lays out the container’s other children by
setting the child component’s includeInLayout property of the component to false:
■ Box, or any of its subclasses: HBox, VBox, DividedBox, HDividedBox, VdividedBox,
Grid, GridItem, GridRow, ControlBar, and ApplicationControlBar,
■ Form
■ Tile and its subclass, Legend
■ ToolBar
When a component’s includeInLayout property is false, Flex does not include it in the
layout calculations for other components, but still lays it out. In other words, Flex does not
reserve space for the component, but still draws it. As a result, the component can appear
underneath the components that follow it in the layout order. To prevent Flex from drawing
the component, you must also set its visible property to false.
Positioning and laying out controls 251
The following example shows the effects of the includeInLayout and visible properties. It
lets you toggle each of these properties independently on the middle of three Panel controls in
a VBox control.
<?xml version="1.0"?>
<!-- components\HiddenBoxLayout.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:VBox>
<mx:Panel id="p1"
title="Panel 1"
backgroundColor="#FF0000"/>
<mx:Panel id="p2"
title="Panel 2"
backgroundColor="#00FF00"/>
<mx:Panel id="p3"
title="Panel 3"
backgroundColor="#0000FF"/>
</mx:VBox>
<mx:HBox>
<mx:Button label="Toggle Panel 2 Visible"
click="{p2.visible=!p2.visible;}"/>
<mx:Button label="Toggle Panel 2 in Layout"
click="{p2.includeInLayout=!p2.includeInLayout;}"/>
</mx:HBox>
</mx:Application>
Run this application and click the buttons to see the results of different combinations of
visible and includeInLayout properties. The example shows the following behaviors:
■ If you include the second Panel control in the layout and make it invisible, Flex reserves
space for it; you see the background of its VBox container in its place.
■ If you do not include the second Panel control in the layout, the VBox resizes and the
HBox with the buttons moves up. If you then include it in the layout, the VBox resizes
again, and the HBox and buttons move down.
■ If you do not include the second Panel control in the layout and make it visible, Flex still
draws it, but does not consider it in laying out the third Panel control, so the two panels
overlap. Because the title of a Panel control has a default alpha of 0.5, you see the
combination of the second and third Panel controls in the second Panel position.
252 Sizing and Positioning Components
Using absolute positioning
Three containers support absolute positioning:
■ Application and Panel controls use absolute positioning if you specify the layout
property as "absolute" (ContainerLayout.ABSOLUTE).
■ The Canvas container always uses absolute positioning.
With absolute positioning, you specify the child control position by using its x and y
properties, or you specify a constraint-based layout; otherwise, Flex places the child at
position 0,0 of the parent container. When you specify the x and y coordinates, Flex
repositions the controls only when you change the property values. The following example
uses absolute positioning to place a VBox control inside a Canvas control:
<?xml version="1.0"?>
<!-- components\CanvasLayout.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
backgroundGradientColors="[#FFFFFF, #FFFFFF]">
<mx:Canvas
width="100" height="100"
backgroundColor="#999999">
<mx:VBox id="b1"
width="80" height="80"
x="20" y="20"
backgroundColor="#A9C0E7">
</mx:VBox>
</mx:Canvas>
</mx:Application>
This example produces the following image:
Positioning and laying out controls 253
When you use absolute positioning, you have full control over the locations of the container’s
children. This lets you overlap components. The following example adds a second VBox to
the previous example so that it partially overlaps the initial box.
<?xml version="1.0"?>
<!-- components\CanvasLayoutOverlap.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
backgroundGradientColors="[#FFFFFF, #FFFFFF]">
<mx:Canvas
width="100" height="100"
backgroundColor="#999999">
<mx:VBox id="b1"
width="80" height="80"
x="20" y="20"
backgroundColor="#A9C0E7">
</mx:VBox>
<mx:VBox id="b2"
width="50" height="50"
x="0" y="50"
backgroundColor="#FF0000">
</mx:VBox>
</mx:Canvas>
</mx:Application>
This example produces the following image:
If you use percentage-based sizing for the children of a control that uses absolute
N OT E
positioning, be aware that percentage-based components resize when the parent
container resizes, and the result may include unwanted overlapping of controls.
254 Sizing and Positioning Components
Using constraint-based layout
You can manage child component size and position simultaneously by using constraint-based
layout, where you anchor the sides or center of a component to positions relative to the
viewable region of the component’s container. The viewable region is the part of the
component that is being displayed, and it can contain child controls, text, images, or other
contents.
For an introduction to using constraint-based layout in Flex Builder, see Getting Started
NO TE
with Flex 2.
You can use constraint-based layout to determine the position and size of the immediate
children of any container that supports absolute positioning.
With constraint-based layout you can do the following:
■ Anchor one or more edges of a component at a pixel offset from the corresponding edge of
its container’s viewable region. The anchored child edge stays at the same distance from
the parent edge when the container resizes. If you anchor both edges in a dimension, such
as top and bottom, the component resizes if the container resizes.
■ Anchor the child’s horizontal or vertical center (or both) at a pixel offset from the center of
the container’s viewable region. The child does not resize in the specified dimension unless
you also use percentage-based sizing.
Creating a constraint-based layout
The following rules specify how to position and size components by using constraint-based
layout:
■ Place the component directly inside a Canvas container, or directly inside an Application
or Panel container with the layout property set to absolute.
■ You can specify a constraint-based layout for any Flex framework component (that is, any
component that extends the UIComponent class).
■ Specify the constraints by using the top, bottom, left, right, horizontalCenter, or
verticalCenter styles.
The top, bottom, left, and right styles specify the distances between the component
sides and the corresponding container sides.
The horizontalCenter and verticalCenter styles specify distance between the
component’s center point and the container’s center, in the specified direction; a negative
number moves the component left or up from the center.
Using constraint-based layout 255
The following example anchors the Form control’s left and right sides 20 pixels from its
container’s sides:
<mx:Form id="myForm" left="20" right="20"/>
■ Do not specify a top or bottom style with a verticalCenter style; the verticalCenter
value overrides the other properties. Similarly, do not specify a left or right style with a
horizontalCenter style.
■ A size determined by constraint-based layout overrides any explicit or percentage-based
size specifications. If you specify left and right constraints, for example, the resulting
constraint-based width overrides any width set by a width or percentWidth property.
Example: Using constraint-based layout for a form
The following example code shows how you can use constraint-based layout for a form. In
this example, the Form control uses a constraint-based layout to position its top just inside the
canvas padding. The form left and right edges are 20 pixels from the Canvas container’s left
and right edges. The HBox that contains the buttons uses a constraint-based layout to place
itself 20 pixels from the Canvas right edge and 10 pixels from the Canvas bottom edge.
If you change the size of your browser or standalone Flash Player, you can see the effects of
dynamically resizing the Application container on the Form layout. The form and the buttons
overlap as the application grows smaller, for example. In an application, you should include
the buttons in the last FormItem of the form, the buttons are separate in the following
example to better show the effects of resizing.
256 Sizing and Positioning Components
<?xml version="1.0"?>
<!-- components\ConstraintLayout.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<!-- Use a Canvas container in the Application to prevent
unnecessary scroll bars on the Application. -->
<mx:Canvas width="100%" height="100%">
<!-- Anchor the top of the form at the top of the canvas.
Anchor the form sides 20 pixels from the canvas sides. -->
<mx:Form id="myForm"
backgroundColor="#DDDDDD"
top="0"
left="20"
right="20">
<mx:FormItem label="Product:" width="100%">
<!-- Specify a fixed width to keep the ComboBox control from
resizing as you change the application size. -->
<mx:ComboBox width="200"/>
</mx:FormItem>
<mx:FormItem label="User" width="100%">
<mx:ComboBox width="200"/>
</mx:FormItem>
<mx:FormItem label="Date">
<mx:DateField/>
</mx:FormItem>
<mx:FormItem width="100%"
direction="horizontal"
label="Hours:">
<mx:TextInput width="75"/>
<mx:Label text="Minutes" width="48"/>
<mx:TextInput width="75"/>
</mx:FormItem>
</mx:Form>
<!-- Anchor the box with the buttons 20 pixels from the canvas
right edge and 10 pixels from the bottom. -->
<mx:HBox id="okCancelBox"
right="20"
bottom="10">
<mx:Button label="OK"/>
<mx:Button label="Cancel"/>
</mx:HBox>
</mx:Canvas>
</mx:Application>
Using constraint-based layout 257
258 Sizing and Positioning Components
9
CHAPTER 9
Using Controls
Controls are user-interface components such as Button, TextArea, and ComboBox controls.
This topic describes how to use controls in a Flex application.
Adobe Flex has two types of controls: basic and data provider. This topic contains an overview
of all Flex controls, and describes the basic Flex controls. For information on data provider
controls, see Chapter 12, “Using Data-Driven Controls,” on page 439.
Contents
About controls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
Working with controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .266
Button control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .269
PopUpButton control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
ButtonBar and ToggleButtonBar controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
LinkBar control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
TabBar control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .283
CheckBox control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
RadioButton control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .288
NumericStepper control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
DateChooser and DateField controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .296
LinkButton control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .307
HSlider and VSlider controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
SWFLoader control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
Image control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .325
VideoDisplay control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .335
ColorPicker control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .342
Alert control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
ProgressBar control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .356
HRule and VRule controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
ScrollBar control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .365
259
About controls
Controls are user-interface components, such as Button, TextArea, and ComboBox controls.
You place controls in containers, which are user-interface components that provide a
hierarchical structure for controls and other containers. Typically, you define a container, and
then insert controls or other containers in it.
At the root of a Flex application is the <mx:Application> tag, which represents a base
container that covers the entire Flash Player drawing surface. You can place controls or
containers directly under the <mx:Application> tag or in other containers. For more
information on containers, see Chapter 13, “Introducing Containers,” on page 491.
Most controls have the following characteristics:
■ MXML API for declaring the control and the values of its properties and events
■ ActionScript API for calling the control’s methods and setting its properties at run time
■ Customizable appearance using styles, skins, and fonts
The following image shows several controls used in a Form container:
Form container
TextInput controls
ComboBox control
Button control
260 Using Controls
The MXML and ActionScript APIs let you create and configure a control. The following
MXML code example creates a TextInput control in a Form container:
<?xml version="1.0"?>
<!-- controls\TextInputInForm.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Form width="300" height="100">
<mx:FormItem label="Card Name">
<mx:TextInput id="cardName"/>
</mx:FormItem>
</mx:Form>
</mx:Application>
This example produces the following image:
Although you commonly use MXML as the language for building Flex applications, you can
also use ActionScript to configure controls. For example, the following code example
populates a DataGrid control by providing an Array of items as the value of the DataGrid
control’s dataProvider property:
<?xml version="1.0"?>
<!-- controls\DataGridConfigAS.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
private function myGrid_initialize():void {
myGrid.dataProvider = [
{Artist:'Steve Goodman', Album:'High and Outside', Price:8.99},
{Artist:'Carole King', Album:'Tapestry', Price:11.99},
{Artist:'The Beach Boys', Album:'Pet Sounds', Price:13.99},
{Artist:'Original Cast', Album:'Camelot', Price:9.99} ];
}
]]>
</mx:Script>
<mx:DataGrid id="myGrid"
width="350" height="150"
color="#7B0974"
creationComplete="myGrid_initialize();"/>
</mx:Application>
About controls 261
This example produces the following image:
About text controls
Several Flex components display text or take text input, as the following table shows:
Control Type of text
Label Noneditable, single-line text field
Text Noneditable, multiline text field
TextInput (Optional) Editable, single-line text field
TextArea (Optional) Editable, multiline text field
RichTextEditor Compound control that contains a multiline text field and controls that let a
user format text by selecting such characteristics as font, size, weight,
alignment, and so on
These controls can display plain text that all has the same appearance. The controls can also
display rich text formatted by using a subset of the standard HTML formatting tags. For
information on using text controls, see Chapter 10, “Using Text Controls,” on page 369.
Using data provider controls
Several Flex components, such as the DataGrid, Tree, and ComboBox controls, take input
data from a data provider. A data provider is a collection of objects, similar to an array. For
example, a Tree control reads data from the data provider to define the structure of the tree
and any associated data assigned to each tree node.
The data provider creates a level of abstraction between Flex components and the data that
you use to populate them. You can populate multiple components from the same data
provider, switch data providers for a component at run time, and modify the data provider so
that changes are reflected by all components that use the data provider.
262 Using Controls
Consider that the data provider is the model, and the Flex components are the view onto the
model. By separating the model from the view, you can change one without changing the
other.
This topic describes the basic controls. For information on data provider controls, see Chapter
12, “Using Data-Driven Controls,” on page 439.
Using menu controls
Several Flex controls create or interact with menus, as the following table shows:
Control Description
Menu A visual menu that can have cascading submenus
MenuBar A horizontal bar with multiple submenus
PopUpMenuButton A Menu control that opens when you click a button
For information on menu controls, see Chapter 11, “Using Menu-Based Controls,” on
page 407
Flex controls
The following table lists all the controls available with Flex:
Control Description For more information
Alert Displays a pop-up alert “Alert control” on page 351
Button Displays a variable-size button that can “Button control” on page 269
include a label, an icon image, or both.
ButtonBar Displays a row of related buttons with a “ButtonBar and
common appearance. ToggleButtonBar controls”
on page 276
CheckBox Shows whether a particular Boolean “CheckBox control”
value is true (checked) or false on page 287
(unchecked).
ComboBox Displays a drop-down list attached to a “ComboBox control”
text field that contains a set of values. on page 458
ColorPicker Displays a selectable drop-down color “DateChooser and DateField
swatch panel (palette). controls” on page 296
DataGrid Displays data in a tabular format. “DataGrid control” on page 467
About controls 263
Control Description For more information
DateChooser Displays a full month of days to let you “DateChooser and DateField
select a date. controls” on page 296
DateField Displays the date with a calendar icon “DateChooser and DateField
on its right side. When a user clicks controls” on page 296
anywhere inside the control, a
DateChooser control pops up and
displays a month of dates.
HorizontalList Displays a horizontal list of items. “HorizontalList control”
on page 450
HRule/VRule Displays a single horizontal rule “HRule and VRule controls”
(HRule) or vertical rule (VRule). on page 361
HSlider/VSlider Lets users select a value by moving a “HSlider and VSlider controls”
slider thumb between the end points of on page 310
the slider track.
Image Imports GIF, JPEG, PNG, SVG, and “Image control” on page 325
SWF files.
Label Displays a noneditable single-line field “LinkButton control”
label. on page 307
LinkBar Displays a horizontal row of LinkButton “LinkBar control” on page 280
controls that designate a series of link
destinations.
LinkButton Displays a simple hypertext link. “LinkButton control”
on page 307
List Displays a scrollable array of choices. “List control” on page 440
Menu Displays a pop-up menu of individually “Handling Menu control events”
selectable choices, much like the File or on page 415
Edit menu of most software
applications.
MenuBar Displays a horizontal menu bar that “MenuBar control” on page 431
contains one or more submenus of
Menu controls.
NumericStepper Displays a dual button control that you “NumericStepper control”
can use to increase or decrease the on page 294
value of the underlying variable.
ProgressBar Provides visual feedback of how much “ProgressBar control”
time remains in the current operation. on page 356
264 Using Controls
Control Description For more information
RadioButton Displays a set of buttons of which “RadioButton control”
exactly one is selected at any time. on page 288
RadioButton Displays a group of RadioButton “Creating a group using the
Group controls with a single click event <mx:RadioButtonGroup> tag”
listener. on page 292
RichTextEditor Includes a multiline editable text field “RichTextEditor control”
and controls for specifying text on page 398
formatting.
ScrollBar Displays horizontal and vertical scroll “ScrollBar control” on page 365
(HScrollBar and bars.
VScrollBar)
SWFLoader Displays the contents of a specified “SWFLoader control”
SWF file or JPEG file. on page 319
TabBar Displays a horizontal row of tabs. “TabBar control” on page 283
Text Displays a noneditable multiline text “TextInput control” on page 393
field.
TextArea Displays an editable text field for user “Using Text Controls”
input that can accept more than a on page 369
single line of input.
TextInput Displays an editable text field for a “TextInput control” on page 393
single line of user input. Can contain
alphanumeric data, but input is
interpreted as a String data type.
TileList Displays a tiled list of items. The items “TileList control” on page 454
are tiled in vertical columns or
horizontal rows.
ToggleButtonBar Displays a row of related buttons with a “ButtonBar and
common appearance. ToggleButtonBar controls”
on page 276
Tree Displays hierarchical data arranged as “Tree control” on page 479
an expandable tree.
VideoDisplay Incorporates streaming media into Flex “VideoDisplay control”
applications. on page 335
About controls 265
Working with controls
Flex controls share a common class hierarchy. Therefore, you use a similar procedure to
configure all controls. This section describes the following topics:
■ “Class hierarchy of controls” on page 266
■ “Sizing controls” on page 266
■ “Positioning controls” on page 267
■ “Changing the appearance of controls” on page 268
Class hierarchy of controls
Flex controls are ActionScript objects derived from the flash.display.Sprite and
mx.core.UIComponent classes, as the following example shows. Controls inherit the
properties, methods, events, styles, and effects of these superclasses:
Sprite
UIComponent
Controls
The Sprite and UIComponent classes are the base classes for all Flex components. Subclasses
of the UIComponent class can have shape, draw themselves, and be invisible. Each subclass
can participate in tabbing, accept low-level events like keyboard and mouse input, and be
disabled so that it does not receive mouse and keyboard input.
For information on the interfaces inherited by controls from the Sprite and UIComponent
classes, see Chapter 6, “Using Flex Visual Components,” on page 133.
Sizing controls
This section briefly describes how Flex sizes controls. For more information on sizing
components, see Chapter 8, “Sizing and Positioning Components,” on page 221.
All controls define rules for determining their size in a Flex application. For example, a Button
control sizes itself to fit its label text and optional icon image, while an Image control sizes
itself to the size of the imported image. Each control has a default height and a default width.
The default size of each standard control is specified in the description of each control.
266 Using Controls
The default size of a control is not necessarily a fixed value. For example, for a Button control,
the default size is large enough to fit its label text and optional icon image. At run time, Flex
calculates the default size of each control and, by default, does not resize a control from its
default size.
Set the height or width attributes in MXML to percentages, such as 50%, or the
percentHeight or percentWidth properties in ActionScript to percentage values, such as 50,
to allow Flex to resize the control in the corresponding direction. Flex attempts to fit the
control to the percentage of its parent container that you specify. If there isn’t enough space
available, the percentages are scaled, while retaining their relative values.
For example, you can set the width of a comments box to scale with its parent container as the
parent container changes size:
<mx:TextInput id="comments" width="100%" height ="20"/>
You can also specify explicit sizes for a control. In MXML or ActionScript by setting the its
height and width properties to numeric pixel values. The following example sets the height
and width of the addr2 TextInput control to 20 pixels and 100 pixels, respectively:
<mx:TextInput id="addr2" width="100" height ="20"/>
To resize a control at run time, use ActionScript to set its width and height properties. For
example, the click event listener for the following Button control sets the width property of
the addr2 TextInput control to increase its width by 10 pixels:
<mx:Button id="button1" label="Slide" height="20"
click="addr2.width+=10;"/>
The preceding technique works even if the width property was originally set as a
NO T E
percentage value. The stored values of the width and height properties are always in
pixels.
Many components have arbitrarily large maximum sizes, which means that Flex can make
them as large as necessary to fit the requirements of your application. While some
components have a defined nonzero minimum size, most have a minimum size of 0. You can
use the maxHeight, maxWidth, minHeight, and minWidth properties to set explicit size ranges
for each component.
Positioning controls
You place controls inside containers. Most containers have predefined layout rules that
automatically determine the position of their children. The Canvas container absolutely
positions its children, and the Application, and Panel containers optionally let you use
absolute or container-relative positioning.
Working with controls 267
To absolutely position a control, you set its x and y properties to specific horizontal and
vertical pixel coordinates within the container. These coordinates are relative to the upper-left
corner of the container, where the upper-left corner is at coordinates (0,0). Values for x and y
can be positive or negative integers. You can use negative values to place a control outside of
the visible area of the container, and then use ActionScript to move the child to the visible
area, possibly as a response to an event.
The following example places the TextInput control 150 pixels to the right and 150 pixels
down from the upper-left corner of a Canvas container:
<mx:TextInput id="addr2" width="100" height ="20" x="150" y="150"/>
To reposition a control within an absolutely-positioned container at run time, you set its x
and y properties. For example, the click event listener for the following Button control
moves the TextInput control down 10 pixels from its current position:
<mx:Button id="button1" label="Slide" height="20" x="0" y="250"
click="addr2.y = addr2.y+10;"/>
For detailed information about control positioning, including container-relative positioning,
see Chapter 8, “Sizing and Positioning Components,” on page 221.
Changing the appearance of controls
Styles, skins, and fonts let you customize the appearance of controls. They describe aspects of
components that you want components to have in common. Each control defines a set of
styles, skins, and fonts that you can set; some are specific to a particular type of control, and
others are more general.
Flex provides several different ways for you to configure the appearance of your controls. For
example, you can set styles for a specific control in the control’s MXML tag, by using
ActionScript, or globally for all instances of a specific control in an application by using the
<mx:Style> tag.
A theme defines the look and feel of a Flex application. A theme can define something as
simple as the color scheme or common font for an application, or it can be a complete
reskinning of all the Flex components. The current theme for your application defines the
styles that you can set on the controls within it. That means some style properties might not
always be settable. For more information, see Chapter 18, “Using Styles and Themes,” on
page 697.
268 Using Controls
Button control
The Button control is a commonly used rectangular button. Button controls look like they
can be pressed, and have a text label, an icon, or both on their face. You can optionally specify
graphic skins for each of several Button states.
You can create a normal Button control or a toggle Button control. A normal Button control
stays in its pressed state for as long as the mouse button is down after you select it. A toggle
Button controls stays in the pressed state until you select it a second time.
Buttons typically use event listeners to perform an action when the user selects the control.
When a user clicks the mouse on a Button control, and the Button control is enabled, it
dispatches a click event and a buttonDown event. A button always dispatches events such as
the mouseMove, mouseOver, mouseOut, rollOver, rollOut, mouseDown, and mouseUp events
whether enabled or disabled.
The following example shows a Button control:
You can use customized graphic skins to customize your buttons to match your application’s
look and functionality. You can give the Button control different image skins for the up,
down, and disabled states, and the skins for these states can differ depending on whether the
button is selected or not selected. The control can change the image skins dynamically.
The following example shows seven Button controls to control video recording and playback
arranged in an HBox layout container. All buttons are in their up state.
The Button control has the following default properties:
Property Default value
Default size A size large enough to hold the label text, and any icon
Minimum size 0
Maximum size No limit
Button control 269
Creating a Button control
You define a Button control in MXML by using the <mx:Button> tag, as the following
example shows. Specify an id value if you intend to refer to a component elsewhere in your
MXML, either in another tag or in an ActionScript block. The following code creates a
Button control with the label “Hello world!”:
<?xml version="1.0"?>
<!-- controls\button\ButtonLabel.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Button id="button1" label="Hello world!" width="100"/>
</mx:Application>
A Button control’s icon, if specified, and label are centered within the bounds of the Button
control. You can position the text label in relation to the icon using the labelPlacement
property, which accepts the values right, left, bottom, and top.
Embedding an icon in a Button control
Flex lets you import graphics into your applications at both compile time and run time.
Button icons must be embedded at compile time rather than referenced at run time. You can
use the @Embed syntax in the icon property value to embed any GIF, JPEG, PNG, SVG, or
SWF file, or you can bind to an image that you defined within a script block by using
[Embed] metadata. If you must reference your button graphic at run time, you can use an
<mx:Image> tag instead of an <mx:Button> tag.
For more information on embedding resources, see Chapter 30, “Embedding Assets,” on
page 1113.
The following code example creates a Button control with a label and an icon:
<?xml version="1.0"?>
<!-- controls\button\ButtonLabelIcon.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Button
label="Icon Button"
icon="@Embed(source='assets/logo.jpg')"/>
</mx:Application>
The icon is in the assets subdirectory of the directory containing the application file. This
results in a button with the icon displayed to the left of the label text:
For an overview of resource embedding, see Chapter 30, “Embedding Assets,” on page 1113.
270 Using Controls
Sizing a Button control
By default, Flex stretches the Button control width to fit the size of its label, any icon, plus 6
pixels of padding around the icon. You can override this default width by explicitly setting the
width property of the Button control to a specific value or to a percentage of its parent
container. If you specify a percentage value, the button resizes between its minimum and
maximum widths as the size of its parent container changes.
If you explicitly size a Button control so that it is not large enough to accommodate its label,
the label is truncated and terminated by an ellipses (...). The full label displays as a tooltip
when you move the mouse over the Button control. If you have also set a tooltip using the
tooltip property, the tooltip is displayed rather than the label text.
Text that is vertically larger than the Button control is also clipped. If you explicitly size a
Button control so that it is not large enough to accommodate its icon, icons larger than the
Button control extend outside the Button control’s bounding box.
Button control user interaction
When a user clicks the mouse on a Button control, the Button control dispatches a click
event, as the following example shows:
<?xml version="1.0"?>
<!-- controls\button\ButtonClick.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<!-- Input field. -->
<mx:TextInput id="myInput" width="150" text=""/>
<!-- Button control that triggers the copy. -->
<mx:Button id="myButton" label="Copy Text"
click="myText.text=myInput.text;"/>
<!-- Output text box. -->
<mx:TextArea id="myText" text="" width="150" height="20"/>
</mx:Application>
In this example, clicking the Button control copies the text from the TextInput control to the
TextArea control.
If a Button control is enabled, it behaves as follows:
■ When the user moves the mouse pointer over the Button control, the Button control
displays its rollover appearance.
■ When the user clicks the Button control, focus moves to the control and the Button
control displays its pressed appearance. When the user releases the mouse button, the
Button control returns to its rollover appearance.
Button control 271
■ If the user moves the mouse pointer off the Button control while pressing the mouse
button, the control’s appearance returns to the original state and it retains focus.
■ If the toggle property is set to true, the state of the Button control does not change until
the user releases the mouse button over the control.
If a Button control is disabled, it displays its disabled appearance, regardless of user
interaction. In the disabled state, all mouse or keyboard interaction is ignored.
Skinning a Button control
You can specify a set of up to eight different image skin properties, where each property
corresponds to a different button state. These skins determine the basic appearance of the
buttons. You can specify images for each of the following button states:
■ Up (the mouse is not over the control)
■ Down (the mouse is over the control and the mouse button is pressed)
■ Over (the mouse hovers over the control)
■ Disabled
■ Selected and up
■ Selected and down
■ Selected and over
■ Selected and disabled
Specifying image skins
You specify the default appearance of a Button control by specifying an up state image (the
upSkin property). All other states use the up state image or the image from another state as
their default. For example, if you do not specify an image for the down state, Flex uses the
image specified for the over state; if you don’t specify an image for the over state, Flex uses the
image for the up state. The selected states are used only for toggle buttons that are selected
(pressed).
The skin image determines the appearance of the button, including its shape. The image can
be GIF, JPEG, PNG, SVG, or SWF file. You can create the skins as independent image files,
or incorporate multiple images in a single SWF file.
Flex must embed the button images in the application’s SWF file at compile time; you cannot
download images from the server at run time. To embed the image, use the @Embed MXML
compiler directive. The following code example shows how to use a GIF file as the up
(default) button image:
upSkin="@Embed(source='assets/buttonUp.gif')"
272 Using Controls
The following code example creates a toggle button with an image for up, down, over, and
disabled states. The button has both a label and an icon.
<?xml version="1.0"?>
<!-- controls\button\ButtonSkin.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Button label="Image Button"
toggle="true"
color="0xFFFFAA"
textRollOverColor="0xAAAA55"
textSelectedColor="0xFFFF00"
upSkin="@Embed(source='assets/buttonUp.gif')"
overSkin="@Embed(source='assets/buttonOver.gif')"
downSkin="@Embed(source='assets/buttonDown.gif')"
disabledSkin="@Embed(source='assets/buttonDisabled.gif')"
icon="@Embed(source='assets/logo.gif')"/>
</mx:Application>
PopUpButton control
The PopUpButton control consists of two horizontal buttons: a main button, and a smaller
button called the pop-up button, which only has an icon. The main button is a Button
control.
The pop-up button, when clicked, opens a second control called the pop-up control. Clicking
anywhere outside the PopUpButton control, or in the pop-up control, closes the pop-up
control
The PopUpButton control adds a flexible pop-up control interface to a Button control. One
common use for the PopUpButton control is to have the pop-up button open a List control or
a Menu control that changes the function and label of the main button, as the following
example shows using a Menu control:
PopUpButton control
Main button Pop-up button
PopUpButton control 273
In this example, the user can choose whether the button puts mail in the Inbox, the Sent
Items folder, or the Trash folder, by selecting from the pop-up menu that appears when the
user clicks the small pop-up button to the right of the main button. The text on the main
button indicates the action it performs, and the text changes each time the user selects a
different item from the menu.
The PopUpButton control is not limited to displaying menus; it can display any Flex control
as the pop-up control. A workflow application that lets users send a document for review, for
example, could use a Tree control as a visual indication of departmental structure. The
PopUpButton control’s pop-up button would display the tree, from which the user could pick
the message recipients.
The control that pops up does not have to affect the main button’s appearance or action; it
can have an independent action, instead. You could create an undo PopUpButton control, for
example, where the main button undoes only the last action, and the pop-up control is a List
control that lets users undo multiple actions by selecting them.
The PopUpButton control is a subclass of the Button control and inherits all of its properties,
styles, events, and methods, with the exception of the toggle property and the styles used for
a selected button.
The control has the following characteristics:
■ The popUp property specifies the pop-up control (for example, List or Menu).
■ The open() and close() methods lets you open and close the pop-up control
programmatically, rather than using the pop-up button.
■ The open and close events are dispatched when the pop-up control opens and closes.
■ You use the popUpSkin and arrowButtonWidth style properties to define the
PopUpButton control’s appearance.
For detailed descriptions, see PopUpButton in Adobe Flex 2 Language Reference.
The PopUpButton control has the following default properties:
Property Default value
Default size Sufficient to accommodate the label and icon on the main button and the
icon on the pop-up button
Minimum size 0
Maximum size Undefined
274 Using Controls
Creating a PopUpButton control
You use the <mx:PopUpButton> tag to define a PopUpButton control in MXML, as the
following example shows. Specify an id value if you intend to refer to a component elsewhere
in your MXML, either in another tag or in an ActionScript block.
In the following example, you use the PopUpButton control to open a Menu control. Once
opened, the Menu control, or any pop-up control, functions just as it would normally. You
define an event listener for the Menu control’s change event to recognize when the user selects
a menu item, as the following example shows:
<?xml version="1.0"?>
<!-- controls\button\PopUpButtonMenu.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
height="600" width="600">
<mx:Script>
<![CDATA[
import mx.controls.*;
import mx.events.*;
private var myMenu:Menu;
// Initialize the Menu control,
// and specify it as the pop up object
// of the PopUpButton control.
private function initMenu():void {
myMenu = new Menu();
var dp:Object = [
{label: "New Folder"},
{label: "Sent Items"},
{label: "Inbox"}
];
myMenu.dataProvider = dp;
myMenu.addEventListener("itemClick", changeHandler);
popB.popUp = myMenu;
}
// Define the event listener for the Menu control's change event.
private function changeHandler(event:MenuEvent):void {
var label:String = event.label;
popTypeB.text=String("Moved to " + label);
popB.label = "Put in: " + label;
popB.close();
}
]]>
</mx:Script>
<mx:VBox>
PopUpButton control 275
<mx:Label text="Main button mimics the last selected menuItem."/>
<mx:PopUpButton id="popB"
label="Edit"
width="135"
creationComplete="initMenu();"/>
<mx:Spacer height="50"/>
<mx:TextInput id="popTypeB"/>
</mx:VBox>
</mx:Application>
User interaction
You navigate the PopUpButton control using the mouse as follows:
■ Moving the mouse over any part of the PopUpButton control highlights the button
border and the main button or the pop-up button.
■ Clicking the button dispatches the click event.
■ Clicking the pop-up button pops up the pop-up control and dispatches an open event.
■ Clicking anywhere outside the PopUpButton control, or in the pop-up control, closes the
pop-up control and dispatches a close event.
The following keystrokes let users navigate the PopUpButton control:
Key Use
Spacebar Behaves like clicking the main button.
Control+Down Arrow Opens the pop-up control and initiates an open event. The pop-up
control’s keyboard handling takes effect.
Control+Up Arrow Closes the pop-up control and initiates a close event.
You cannot use the Tab key to leave an opened pop-up control; you must make a
N OT E
selection or close the control with the Control+Up Arrow key combination.
ButtonBar and ToggleButtonBar
controls
The ButtonBar and ToggleButtonBar controls define a horizontal or vertical row of related
buttons with a common appearance. The controls define a single event, the itemClick event,
that is dispatched when any button in the control is selected.
276 Using Controls
The ButtonBar control defines group of buttons that do not retain a selected state. When you
select a button in a ButtonBar control, the button changes its appearance to the selected state;
when you release the button, it returns to the deselected state.
The ToggleButtonBar control defines a group buttons that maintain their state, either selected
or deselected. Only one button in the ToggleButtonBar control can be in the selected state.
That means when you select a button in a ToggleButtonBar control, the button stays in the
selected state until you select a different button.
If you set the unselectable property of the ToggleButtonBar control to true, selecting the
currently selected button deselects it. By default the unselectable properties false.
The following image shows an example of a ButtonBar control that defines a set of buttons:
The following image shows an example of a ToggleButtonBar control that defines a set of
buttons, where the Dreamweaver button is the currently selected button in the control:
A ButtonBar and ToggleButtonBar control have the following default properties:
Property Default value
Preferred size Wide enough to contain all buttons with their label text and icons, if any,
plus any padding and separators, and high enough to accommodate the
button height.
Control resizing The controls do not resize by default. Specify percentage sizes if you want
rules your ButtonBar to resize based on the size of its parent container.
Padding 0 pixels for the top, bottom, left, and right properties.
ButtonBar and ToggleButtonBar controls 277
Creating a ButtonBar control
You create a ButtonBar control in MXML using the <mx:ButtonBar> tag, as the following
example shows:
<?xml version="1.0"?>
<!-- controls\bar\BBarSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
<mx:ButtonBar borderStyle="solid" horizontalGap="5">
<mx:dataProvider>
<mx:String>Flash</mx:String>
<mx:String>Director</mx:String>
<mx:String>Dreamweaver</mx:String>
<mx:String>ColdFusion</mx:String>
</mx:dataProvider>
</mx:ButtonBar>
</mx:Application>
This example creates a row of four Button controls, as shown in the image in the section
“ButtonBar and ToggleButtonBar controls” on page 276.
To create a ToggleButtonBar control, replace the <mx:ButtonBar> tag with the
<mx:ToggleButtonBar> tag. Otherwise, the syntax is the same for both controls.
You use the dataProvider property to specify the labels of the four buttons. You can also
populate the dataProvider property with an Array of Objects; where each object can have
up to three fields: label, icon, and tooltip.
In the following example, you use an Array of Objects to specify a label and icon for each
button:
<?xml version="1.0"?>
<!-- controls\bar\BBarLogo.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:ButtonBar borderStyle="solid" horizontalGap="5">
<mx:dataProvider>
<mx:Object label="Flash"
icon="@Embed(source='assets/Flashlogo.gif')"/>
<mx:Object label="Director"
icon="@Embed(source='assets/Dirlogo.gif')"/>
<mx:Object label="Dreamweaver"
icon="@Embed(source='assets/Dlogo.gif')"/>
<mx:Object label="ColdFusion"
icon="@Embed(source='assets/CFlogo.gif')"/>
</mx:dataProvider>
</mx:ButtonBar>
</mx:Application>
278 Using Controls
A ButtonBar or ToggleButtonBar control creates Button controls based on the value of its
dataProvider property. Even though ButtonBar and ToggleButtonBar are subclasses of
Container, do not use methods such as Container.addChild() and
Container.removeChild() to add or remove Button controls. Instead, use methods such as
addItem() and removeItem() to manipulate the dataProvider property. A ButtonBar or
ToggleButtonBar control automatically adds or removes the necessary children based on
changes to the dataProvider property.
Handling ButtonBar events
The ButtonBar and ToggleButtonBar controls dispatch a itemClick event when you select a
button. The event object passed to the event listener is of type ItemClickEvent. From within
the event listener, you can access properties of the event object to determine the index of the
selected button, where the first button is at index 0, and other information. For more
information on the event object, see the description of the ItemClickEvent class in Adobe
Flex 2 Language Reference.
ButtonBar and ToggleButtonBar controls 279
The ButtonBar control in the following example defines an event listener for the itemClick
event:
<?xml version="1.0"?>
<!-- controls\bar\BBarEvent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
<mx:Script>
<![CDATA[
import mx.events.ItemClickEvent;
private function clickHandler(event:ItemClickEvent):void {
myTA.text="Selected button index: " +
String(event.index) + "\n" +
"Selected button label: " +
event.label;
}
]]>
</mx:Script>
<mx:TextArea id="myTA" width="200" height="100"/>
<mx:ButtonBar
borderStyle="solid"
horizontalGap="5"
itemClick="clickHandler(event);">
<mx:dataProvider>
<mx:String>Flash</mx:String>
<mx:String>Director</mx:String>
<mx:String>Dreamweaver</mx:String>
<mx:String>ColdFusion</mx:String>
</mx:dataProvider>
</mx:ButtonBar>
</mx:Application>
In this example, the event listener displays the index and label of the selected button in a
TextArea control in response to a itemClick event.
LinkBar control
A LinkBar control defines a horizontal or vertical row of LinkButton controls that designate a
series of link destinations. You typically use a LinkBar control to control the active child
container of a ViewStack container, or to create a standalone set of links.
The following shows an example of a LinkBar control that defines a set of links:
280 Using Controls
A LinkBar control has the following default properties:
Property Default value
Preferred size A width wide enough to contain all label text, plus any padding and
separators, and the height of the tallest child.
Control resizing LinkBar controls do not resize by default. Specify percentage sizes if you
rules want your LinkBar to resize based on the size of its parent container.
Padding 2 pixels for the top, bottom, left, and right properties.
Creating a LinkBar control
One of the most common uses of a LinkBar control is to control the active child of a
ViewStack container. For an example, see “ViewStack navigator container” on page 628.
You can also use a LinkBar control on its own to create a set of links in your application. In
the following example, you define a itemClick handler for the LinkBar control to respond to
user input, and use the dataProvider property of the LinkBar to specify its label text. Use
the following example code to create the LinkBar control shown in the previous image:
<?xml version="1.0"?>
<!-- controls\bar\LBarSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:LinkBar borderStyle="solid"
itemClick="navigateToURL(new URLRequest('http://www.adobe.com/' +
String(event.label).toLowerCase()), '_blank');">
<mx:dataProvider>
<mx:String>Flash</mx:String>
<mx:String>Director</mx:String>
<mx:String>Dreamweaver</mx:String>
<mx:String>ColdFusion</mx:String>
</mx:dataProvider>
</mx:LinkBar>
</mx:Application>
In this example, you use the <mx:dataProvider> and <mx:Array> tags to define the label
text. The event object passed to the itemClick handler contains the label selected by the user.
The handler for the itemClick event constructs an HTTP request to the Adobe website
based on the label, and opens that page in a new browser window.
LinkBar control 281
You can also bind data to the <mx:dataProvider> tag to populate the LinkBar control, as the
following example shows:
<?xml version="1.0"?>
<!-- controls\bar\LBarBinding.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable]
private var linkData:ArrayCollection = new ArrayCollection([
"Flash", "Director", "Dreamweaver", "ColdFusion"
]);
]]>
</mx:Script>
<mx:LinkBar
horizontalAlign="right"
borderStyle="solid"
itemClick="navigateToURL(new URLRequest('http://www.adobe.com/' +
String(event.label).toLowerCase()), '_blank');">
<mx:dataProvider>
{linkData}
</mx:dataProvider>
</mx:LinkBar>
</mx:Application>
In this example, you define the data for the LinkBar control as a variable in ActionScript, and
then you bind that variable to the <mx:dataProvider> tag. You could also bind to the
<mx:dataProvider> tag from a Flex data model, from a web service response, or from any
other type of data model.
A LinkBar control creates LinkButton controls based on the value of its dataProvider
property. Even though LinkBar is a subclass of Container, do not use methods such as
Container.addChild() and Container.removeChild() to add or remove LinkButton
controls. Instead, use methods such as addItem() and removeItem() to manipulate the
dataProvider property. A LinkBar control automatically adds or removes the necessary
children based on changes to the dataProvider property.
282 Using Controls
TabBar control
A TabBar control defines a horizontal or vertical row of tabs. The following shows an example
of a TabBar control:
As with the LinkBar control, you can use a TabBar control to control the active child
container of a ViewStack container. The syntax for using a TabBar control to control the
active child of a ViewStack container is the same as for a LinkBar control. For an example, see
“ViewStack navigator container” on page 628.
While a TabBar control is similar to a TabNavigator container, it does not have any children.
For example, you use the tabs of a TabNavigator container to select its visible child container.
You can use a TabBar control to set the visible contents of a single container to make that
container’s children visible or invisible based on the selected tab.
A TabBar control has the following default properties:
Property Default value
Preferred size A width wide enough to contain all label text, plus any padding, and a height
tall enough for the label text.
The default tab height is determined by the font, style, and skin applied to
the control. If you set an explicit height using the tabHeight property, that
value overrides the default value.
Control resizing TabBar controls do not resize by default. Specify percentage sizes if you
rules want your TabBar to resize based on the size of its parent container.
Padding 0 pixels for the left and right properties.
Creating a TabBar control
You use the <mx:TabBar> tag to define a TabBar control in MXML. Specify an id value if you
intend to refer to a component elsewhere in your MXML, either in another tag or in an
ActionScript block.
TabBar control 283
You specify the data for the TabBar control using the <mx:dataProvider> and <mx:Array>
child tags of the <mx:TabBar> tag. The <mx:dataProvider> tag lets you specify data in
several different ways. In the simplest case for creating a TabBar control, you use the
<mx:dataProvider>, <mx:Array>, and <mx:String> tags to specify the text for each tab, as
the following example shows:
<?xml version="1.0"?>
<!-- controls\bar\TBarSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:TabBar>
<mx:dataProvider>
<mx:String>Alabama</mx:String>
<mx:String>Alaska</mx:String>
<mx:String>Arkansas</mx:String>
</mx:dataProvider>
</mx:TabBar>
</mx:Application>
The <mx:String> tags define the text for each tab in the TabBar control.
You can also use the <mx:Object> tag to define the entries as an array of objects, where each
object contains a label property and an associated data value, as the following example
shows:
<?xml version="1.0"?>
<!-- controls\bar\TBarObject.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:TabBar>
<mx:dataProvider>
<mx:Object label="Alabama" data="Montgomery"/>
<mx:Object label="Alaska" data="Juneau"/>
<mx:Object label="Arkansas" data="Little Rock"/>
</mx:dataProvider>
</mx:TabBar>
</mx:Application>
The label property contains the state name and the data property contains the name of its
capital. The data property lets you associate a data value with the text label. For example, the
label text could be the name of a color, and the associated data value could be the numeric
representation of that color.
284 Using Controls
By default, Flex uses the value of the label property to define the tab text. If the object does
not contain a label property, you can use the labelField property of the TabBar control to
specify the property name containing the tab text, as the following example shows:
<?xml version="1.0"?>
<!-- controls\bar\TBarLabel.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:TabBar labelField="state">
<mx:dataProvider>
<mx:Object state="Alabama" data="Montgomery"/>
<mx:Object state="Alaska" data="Juneau"/>
<mx:Object state="Arkansas" data="Little Rock"/>
</mx:dataProvider>
</mx:TabBar>
</mx:Application>
Passing data to a TabBar control
Flex lets you populate a TabBar control from an ActionScript variable definition or from a
Flex data model. When you use a variable, you can define it to contain one of the following:
■ A label (string)
■ A label (string) paired with data (scalar value or object)
The following example populates a TabBar control from a variable:
<?xml version="1.0"?>
<!-- controls\bar\TBarVar.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable]
private var STATE_ARRAY:ArrayCollection = new ArrayCollection([
{label:"Alabama", data:"Montgomery"},
{label:"Alaska", data:"Juneau"},
{label:"Arkansas", data:"LittleRock"}
]);
]]>
</mx:Script>
<mx:TabBar >
<mx:dataProvider>
{STATE_ARRAY}
</mx:dataProvider>
</mx:TabBar>
</mx:Application>
TabBar control 285
You can also bind a Flex data model to the dataProvider property. For more information on
using data models, see Chapter 39, “Storing Data,” on page 1269.
Handling TabBar control events
The TabBar control defines a itemClick event that is broadcast when a user selects a tab. The
event object contains the following properties:
■ label String containing the label of the selected tab.
■ index Number containing the index of the selected tab. Indexes are numbered from 0
to n - 1, where n is the total number of tabs. The default value is 0, corresponding to the
first tab.
The following example code shows a handler for the itemClick event for this TabBar
control:
<?xml version="1.0"?>
<!-- controls\bar\TBarEvent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.events.ItemClickEvent;
import mx.controls.TabBar;
import mx.collections.ArrayCollection;
[Bindable]
private var STATE_ARRAY:ArrayCollection = new ArrayCollection([
{label:"Alabama", data:"Montgomery"},
{label:"Alaska", data:"Juneau"},
{label:"Arkansas", data:"LittleRock"}
]);
private function clickEvt(event:ItemClickEvent):void {
// Access target TabBar control.
var targetComp:TabBar = TabBar(event.currentTarget);
forClick.text="label is: " + event.label + " index is: " +
event.index + " capital is: " +
targetComp.dataProvider[event.index].data;
}
]]>
</mx:Script>
<mx:TabBar id="myTB" itemClick="clickEvt(event);">
<mx:dataProvider>
{STATE_ARRAY}
</mx:dataProvider>
286 Using Controls
</mx:TabBar>
<mx:TextArea id="forClick" width="150"/>
</mx:Application>
In this example, every itemClick event updates the TextArea control with the tab label,
selected index, and the selected data from the TabBar control’s dataProvider Array.
CheckBox control
The CheckBox control is a commonly used graphical control that can contain a check mark
or be unchecked (empty). You can use CheckBox controls wherever you need to gather a set of
true or false values that aren’t mutually exclusive.
You can add a text label to a CheckBox control and place it to the left, right, top, or bottom of
the check box. Flex clips the label of a CheckBox control to fit the boundaries of the control.
The following image shows a checked CheckBox control:
For the code used to generate this example, see “Creating a CheckBox control” on page 288.
When a user clicks a CheckBox control or its associated text, the CheckBox control changes
its state from checked to unchecked, or from unchecked to checked.
A CheckBox control can have one of two disabled states, checked or unchecked. By default, a
disabled CheckBox control displays a different background and check mark color than an
enabled CheckBox control.
The CheckBox control has the following default properties:
Property Default value
Default size A size large enough to hold the label
Minimum size 0
Maximum size No limit
CheckBox control 287
Creating a CheckBox control
You use the <mx:CheckBox> tag to define a CheckBox control in MXML, as the following
example shows. Specify an id value if you intend to refer to a component elsewhere in your
MXML, either in another tag or in an ActionScript block.
<?xml version="1.0"?>
<!-- controls\checkbox\CBSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:VBox>
<mx:CheckBox width="100" label="Employee?"/>
</mx:VBox>
</mx:Application>
You can also use the selected property to generate a checkbox that is checked by default:
<?xml version="1.0"?>
<!-- controls\checkbox\CBSelected.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:VBox>
<mx:CheckBox width="100" label="Employee?" selected="true"/>
</mx:VBox>
</mx:Application>
CheckBox control user interaction
When a CheckBox control is enabled and the user clicks it, the control receives focus and
displays its checked or unchecked appearance, depending on its initial state. The entire area of
the CheckBox control is the click area; if the CheckBox control’s text is larger than its icon,
the clickable regions are above and below the icon.
If the user moves the mouse pointer outside the area of the CheckBox control or its label
while pressing the mouse button, the appearance of the CheckBox control returns to its
original state and the control retains focus. The state of the CheckBox control does not
change until the user releases the mouse button over the control.
Users cannot interact with a CheckBox control when it is disabled.
RadioButton control
The RadioButton control is a single choice in a set of mutually exclusive choices. A
RadioButton group is composed of two or more RadioButton controls with the same group
name. Only one member of the group can be selected at any given time. Selecting an
unselected group member deselects the currently selected RadioButton control in the group.
288 Using Controls
About the RadioButton control
The following example shows a RadioButton group with three RadioButton controls:
For the code used to generate this example, see “Creating a RadioButton control”
on page 289.
The RadioButton control has the following default properties:
Property Default value
Default size Wide enough to display the text label of the control
Minimum size 0
Maximum size Undefined
Creating a RadioButton control
You define a RadioButton control in MXML using the <mx:RadioButton> tag, as the
following example shows. Specify an id value if you intend to refer to a component elsewhere
in your MXML, either in another tag or in an ActionScript block.
<?xml version="1.0"?>
<!-- controls\button\RBSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:RadioButton groupName="cardtype"
id="americanExpress"
label="American Express"
width="150"/>
<mx:RadioButton groupName="cardtype"
id="masterCard"
label="MasterCard"
width="150"/>
<mx:RadioButton groupName="cardtype"
id="visa"
label="Visa"
width="150"/>
</mx:Application>
This code results in the application shown in “About the RadioButton control” on page 289.
RadioButton control 289
For each RadioButton control in the group, you can optionally define an event listener for the
button’s click event. When a user selects a RadioButton control, Flex calls the event listener
associated with the button for the click event, as the following code example shows:
<?xml version="1.0"?>
<!-- controls\button\RBEvent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import flash.events.Event;
private function handleAmEx(event:Event):void {
// Handle event.
myTA.text="Got Amex";
}
private function handleMC(event:Event):void {
// Handle event.
myTA.text="Got Amex";
}
private function handleVisa(event:Event):void {
// Handle event.
myTA.text="Got Amex";
}
]]>
</mx:Script>
<mx:RadioButton groupName="cardtype"
id="americanExpress"
label="American Express"
width="150"
click="handleAmEx(event);"/>
<mx:RadioButton groupName="cardtype"
id="masterCard"
label="MasterCard"
width="150"
click="handleMC(event);"/>
<mx:RadioButton groupName="cardtype"
id="visa"
label="Visa"
width="150"
click="handleVisa(event);"/>
<mx:TextArea id="myTA"/>
</mx:Application>
290 Using Controls
RadioButton user interaction
If a RadioButton control is enabled, when the user moves the mouse pointer over an
unselected RadioButton control, the button displays its rollover appearance. When the user
clicks an unselected RadioButton control, the input focus moves to the control and the
button displays its false pressed appearance. When the mouse button is released, the button
displays the true state appearance. The previously selected RadioButton control in the group
returns to its false state appearance.
If the user moves the mouse pointer off the RadioButton control while pressing the mouse
button, the control’s appearance returns to the false state and the control retains input focus.
If a RadioButton control is not enabled, the RadioButton control and RadioButton group
display the disabled appearance, regardless of user interaction. In the disabled state, all mouse
or keyboard interaction is ignored.
The RadioButton and RadioButtonGroup controls have the following keyboard navigation
features:
Key Action
Control+Arrow keys Move focus among the buttons without selecting a button.
Spacebar Select a button.
RadioButton control 291
Creating a group using the <mx:RadioButtonGroup>
tag
The previous example created a RadioButton group using the groupName property of each
RadioButton control. You can also create a RadioButton group using the RadioButtonGroup
control, as the following example shows:
<?xml version="1.0"?>
<!-- controls\button\RBGroupSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.events.ItemClickEvent;
private function handleCard(event:ItemClickEvent):void {
//Handle event.
}
]]>
</mx:Script>
<mx:RadioButtonGroup id="cardtype" itemClick="handleCard(event);"/>
<mx:RadioButton groupName="cardtype"
id="americanExpress"
value="AmEx"
label="American Express"
width="150"/>
<mx:RadioButton groupName="cardtype"
id="masterCard"
value="MC"
label="MasterCard"
width="150"/>
<mx:RadioButton groupName="cardtype"
id="visa"
value="Visa"
label="Visa"
width="150"/>
</mx:Application>
292 Using Controls
In this example, you use the id property of the <mx:RadioButtonGroup> tag to define the
group name and the single itemClick event listener for all buttons in the group. The id
property is required when you use the <mx:RadioButtonGroup> tag. The itemClick event
listener for the group can determine which button was selected, as the following example
shows:
<?xml version="1.0"?>
<!-- controls\button\RBGroupEvent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.ItemClickEvent;
private function handleCard(event:ItemClickEvent):void {
if (event.currentTarget.selectedValue == "AmEx") {
Alert.show("You selected American Express")
}
else {
if (event.currentTarget.selectedValue == "MC") {
Alert.show("You selected Master Card")
}
else {
Alert.show("You selected Visa")
}
}
}
]]>
</mx:Script>
<mx:RadioButtonGroup id="cardtype" itemClick="handleCard(event);"/>
<mx:RadioButton groupName="cardtype"
id="americanExpress"
value="AmEx"
label="American Express"
width="150"/>
<mx:RadioButton groupName="cardtype"
id="masterCard"
value="MC"
label="MasterCard"
width="150"/>
<mx:RadioButton groupName="cardtype"
id="visa"
value="Visa"
label="Visa"
width="150"/>
</mx:Application>
RadioButton control 293
This code results in the following output when you select the American Express button:
In the itemClick event listener, the selectedValue property of the RadioButtonGroup
control in the event object is set to the value of the value property of the selected
RadioButton control. If you omit the value property, Flex sets the selectedValue property
to the value of the label property.
You can still define a click event listener for the individual buttons, even though you also
define one for the group.
NumericStepper control
You can use the NumericStepper control to select a number from an ordered set. The
NumericStepper control consists of a single-line input text field and a pair of arrow buttons
for stepping through the valid values; you can also use the Up Arrow and Down Arrow keys to
cycle through the values.
The following example shows a NumericStepper control:
For the code used to create this image, see “Creating a NumericStepper control” on page 295.
If the user clicks the up arrow, the value displayed is increased by one unit of change. If the
user holds down the arrow, the value increases or decreases until the user releases the mouse
button. When the user clicks the arrow, it is highlighted to provide feedback to the user.
Users can also type a legal value directly into the text field. Although editable ComboBox
controls provide similar functionality, NumericStepper controls are sometimes preferred
because they do not require a drop-down list that can obscure important data.
NumericStepper control arrows always appear to the right of the text field.
294 Using Controls
The NumericStepper control has the following default properties:
Property Default value
Default size Wide enough to display the maximum number of digits used by the control
Minimum size Based on the size of the text
Maximum size Undefined
Creating a NumericStepper control
You define a NumericStepper control in MXML using the <mx:NumericStepper> tag, as the
following example shows. Specify an id value if you intend to refer to a component elsewhere
in your MXML, either in another tag or in an ActionScript block.
<?xml version="1.0"?>
<!-- controls\numericstepper\NumStepSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:NumericStepper id="nstepper1" value="6" stepSize="2"/>
</mx:Application>
Sizing a NumericStepper control
The up and down arrow buttons in the NumericStepper control do not change size when the
control is resized. If the NumericStepper control is sized greater than the default height, the
associated stepper buttons appear pinned to the top and the bottom of the control.
User interaction
If the user clicks the up or down arrow button, the value displayed is increased by one unit of
change. If the user presses either of the arrow buttons for more than 200 milliseconds, the
value in the input field increases or decreases, based on step size, until the user releases the
mouse button or the maximum or minimum value is reached.
Keyboard navigation
The NumericStepper control has the following keyboard navigation features:
Key Description
Down Arrow Value decreases by one unit.
Up Arrow Value increases by one unit.
NumericStepper control 295
Key Description
Left Arrow Moves the insertion point to the left within the NumericStepper control’s
text field.
Right Arrow Moves the insertion point to the right within the Numeric Stepper control’s
text field.
In order to use the keyboard to navigate through the stepper, it must have focus.
DateChooser and DateField controls
The DateChooser and DateField controls let users select dates from graphical calendars. The
DateChooser control user interface is the calendar. The DateField control has a text field that
uses a date chooser popup to select the date; as a result. The DateField properties are a
superset of the DateChooser properties.
For complete reference information, see DateChooser and DateField in Adobe Flex 2 Language
Reference.
About the DateChooser control
The DateChooser control displays the name of a month, the year, and a grid of the days of the
month, with columns labeled for the days of the week. This control is useful in applications
where you want a continually visible calendar. The user can select a single date from the grid.
The control contains forward and back arrow buttons to let you change the month and year.
You can disable the selection of certain dates, and limit the display to a range of dates.
The following image shows a DateChooser control:
Changing the displayed month does not change the selected date. Therefore, the currently
selected date might not always be visible. The DateChooser control resizes as necessary to
accommodate the width of the weekday headings. Therefore, if you use day names, instead of
letters, as headings, the calendar will be wide enough to show the full day names.
296 Using Controls
The DateChooser control has the following default properties:
Property Default value
Default size A size large enough to hold the calendar, and wide enough to display the
day names
Minimum size 0
Maximum size No limit
About the DateField control
The DateField control is a text field that displays the date with a calendar icon on its right
side. When a user clicks anywhere inside the bounding box of the control, a date chooser that
is identical to the DateChooser control pops up. If no date has been selected, the text field is
blank and the current month is displayed in the date chooser.
When the date chooser is open, users can click the month scroll buttons to scroll through
months and years, and select a date. When the user selects a date, the date chooser closes and
the text field displays the selected date.
This control is useful in applications where you want a calendar selection tool, but want to
minimize the space the date information takes up.
The following example shows two images of a DateField control. On the left is a control with
the date chooser closed; the calendar icon appears on the right side of the text box. To the
right is a DateField control with the date chooser open.
You can use the DateField control anywhere you want a user to select a date. For example, you
can use a DateField control in a hotel reservation system, with certain dates selectable and
others disabled. You can also use the DateField control in an application that displays current
events, such as performances or meetings, when a user selects a date.
DateChooser and DateField controls 297
The DateField has the same default properties as the DateChooser for its expanded date
chooser. It has the following default properties for the collapsed control:
Property Default value
Default size A size large enough to hold the formatted date and the calendar icon
Minimum size 0
Maximum size No limit
Creating a DateChooser or DateField control
You define a DateChooser control in MXML using the <mx:DateChooser> tag. You define a
DateField control in MXML using the <mx:DateField> tag. Specify an id value if you
intend to refer to a component elsewhere in your MXML, either in another tag or an
ActionScript block.
The following example creates a DateChooser control; to create a DateField control, simply
change <mx:DateChooser> to <mx:DateField>. The example uses the change event of the
DateChooser control to display the selected date in several different formats.
<?xml version="1.0"?>
<!-- controls\date\DateChooserEvent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.events.CalendarLayoutChangeEvent;
private function useDate(eventObj:CalendarLayoutChangeEvent):void {
// Make sure selectedDate is not null.
if (eventObj.currentTarget.selectedDate == null) {
return
}
//Access the Date object from the event object.
day.text=eventObj.currentTarget.selectedDate.getDay();
date.text=eventObj.currentTarget.selectedDate.getDate();
month.text=eventObj.currentTarget.selectedDate.getMonth();
year.text=eventObj.currentTarget.selectedDate.getFullYear();
wholeDate.text=
eventObj.currentTarget.selectedDate.getFullYear() +
"/" +
(eventObj.currentTarget.selectedDate.getMonth()+1) +
"/" + eventObj.currentTarget.selectedDate.getDate();
}
]]>
</mx:Script>
298 Using Controls
<mx:DateChooser id="date1" change="useDate(event)"/>
<mx:Form>
<mx:FormItem label="Day">
<mx:TextInput id="day" width="100"/>
</mx:FormItem>
<mx:FormItem label="Day of month">
<mx:TextInput id="date" width="100"/>
</mx:FormItem>
<mx:FormItem label="Month">
<mx:TextInput id="month" width="100"/>
</mx:FormItem>
<mx:FormItem label="Year">
<mx:TextInput id="year" width="100"/>
</mx:FormItem>
<mx:FormItem label="Date">
<mx:TextInput id="wholeDate" width="300"/>
</mx:FormItem>
</mx:Form>
</mx:Application>
Notice that the first line of the event listener determines if the selectedDate property is null.
This check is necessary because selecting the currently selected date deselects it, sets the
selectedDate property to null, then dispatches the change event.
The code that determines the value of the wholeDate field adds 1 to the month number
NO TE
because the DateChooser control uses a zero-based month system, where January is
month 0 and December is month 11.
Using the Date class
The DateChooser and DateField controls use the selectedDate property to store the
currently selected date, as an object of type Date. You can create Date objects to represent date
and time values, or access the Date in the selectedDate property.
The Date class has many methods that you can use to manipulate a date. For more
information on the Date class, see the Adobe Flex 2 Language Reference.
In MXML you can create and configure a Date object using the <mx:Date> tag. This tag
exposes the setter methods of the Date class as MXML properties so that you can initialize a
Date object. For example, the following code creates a DateChooser control, and sets the
selected date to April 10, 2005 (notice that months are indexed starting at 0 for the
DateChooser control):
<mx:DateChooser id="date1">
<mx:selectedDate>
<mx:Date month="9" date="10" year="2005"/>
DateChooser and DateField controls 299
</mx:selectedDate>
</mx:DateChooser>
The following example uses inline ActionScript to set the initial selected date for a DateField
control:
<mx:DateField id="date3" selectedDate="{new Date (2005, 9, 10)}"/>
You can also set the selectedDate property in a function, as the following example shows:
<mx:Script>
<![CDATA[
private function initDC():void {
date2.selectedDate=new Date (2003, 3, 10);
}
]]>
</mx:Script>
<mx:DateChooser id="date2" creationComplete="initDC();"/>
You can use property notation to access the ActionScript setter and getter methods of the
selectedDate property Date object. For example, the following line displays the four-digit
year of the selected date in a text box.
<mx:TextInput text="{date1.selectedDate.fullYear}"/>
Specifying header, weekday, and today’s day text
styles
The following date chooser properties let you specify text styles for regions of the control:
■ headerStyleName
■ weekDayStyleName
■ todayStyleName
These properties let you specify styles for the text in the header, week day list and today’s date.
You cannot use these properties to set non-text styles such as todayColor.
300 Using Controls
The following example defines a DateChooser control that has bold, blue header text in a 16-
pixel Times New Roman font. The day of week headers are in bold, italic, green, 15-pixel
Courier text, and today’s date is bold, orange, 12-pixel Times New Roman text. Today’s date
background color is grey, and is set directly in the mx:DateChooser tag.
<?xml version="1.0"?>
<!-- controls\date\DateChooserStyles.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Style>
.myHeaderStyle{
color:#6666CC;
font-family:Times New Roman, Times, serif;
font-size:16px; font-weight:bold;}
.myTodayStyle{
color:#CC6633;
font-family:Times New Roman, Times, serif;
font-size:12px; font-weight:bold;}
.myDayStyle{
color:#006600;
font-family:Courier New, Courier, mono;
font-size:15px; font-style:italic; font-weight:bold;}
</mx:Style>
<mx:DateChooser
headerStyleName="myHeaderStyle"
todayStyleName="myTodayStyle"
todayColor="#CCCCCC"
weekDayStyleName="myDayStyle"/>
</mx:Application>
Specifying selectable dates
The DateChooser control has the following properties that let you specify which dates a user
can select:
Property Description
disabledDays An array of days of the week that the user cannot select. Often used to
disable weekend days.
disabledRange An array of dates that the user cannot select. The array can contain
individual Date objects, objects specifying date ranges, or both.
selectableRange A single range of dates that the user can select. The user can navigate only
among the months that include this range; in these months any dates
outside the range are disabled. Use the disabledRange property to disable
dates within the selectable range.
DateChooser and DateField controls 301
The following example shows a DateChooser control that has the following characteristics:
■ The selectableRange property limits users to selecting dates in the range January 1 -
March 15, 2006. Users can only navigate among the months of January through March
2006.
■ The disabledRanges property prevents users from selecting January 11 or any day in the
range January 23 - February 10.
■ The disabledDays property prevents users from selecting Saturdays or Sundays.
<?xml version="1.0"?>
<!-- controls\date\DateChooserStyles.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:DateChooser
selectableRange="{{rangeStart: new Date(2006,0,1),
rangeEnd: new Date(2006,2,15)}}"
disabledRanges="{[new Date(2006,0,11),
{rangeStart: new Date(2006,0,23), rangeEnd: new Date(2006,1,10)}]}"
disabledDays="{[0,6]}"/>
</mx:Application>
Setting DateChooser and DateField properties in
ActionScript
Properties of the DateChooser and DateField controls take values that are scalars, Arrays, and
Date objects. While you can set most of these properties in MXML, it can be easier to set
some in ActionScript.
302 Using Controls
For example, the following code example uses an array to set the disabledDays property so
that Saturday and Sunday are disabled, which means that they cannot be selected in the
calendar. This example sets the disabledDays property in two different ways: using tags and
using tag attributes:
<?xml version="1.0"?>
<!-- controls\date\DateChooserDisabledOption.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<!-- Use tags.-->
<mx:DateField>
<mx:disabledDays>
<mx:Number>0</mx:Number>
<mx:Number>6</mx:Number>
</mx:disabledDays>
</mx:DateField>
<!-- Use tag attributes.-->
<mx:DateField disabledDays="[0,6]"/>
</mx:Application>
DateChooser and DateField controls 303
The following example sets the dayNames, firstDayOfWeek, headerColor, and
selectableRange properties of a DateChooser control using an initialize event:
<?xml version="1.0"?>
<!-- controls\date\DateChooserInitializeEvent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.events.DateChooserEvent;
private function dateChooser_init():void {
myDC.dayNames=['Sun', 'Mon', 'Tue',
'Wed', 'Th', 'Fri', 'Sat'];
myDC.firstDayOfWeek = 3;
myDC.setStyle("headerColor", 0xff0000);
myDC.selectableRange = {rangeStart: new Date(2004,0,1),
rangeEnd: new Date(2007,0,10)};
}
private function onScroll():void {
myDC.setStyle("fontStyle", "italic");
}
]]>
</mx:Script>
<mx:DateChooser id="myDC"
width="200"
creationComplete="dateChooser_init();"
scroll="onScroll();"/>
</mx:Application>
To set the selectableRange property, the code creates two Date objects that represent the
first date and last date of the range. Users can only select dates within the specified range. This
example also changes the fontStyle of the DateChooser control to italics after the first
time the user scrolls it.
Formatting dates with the DateField control
You can use the formatString property of the DateField control to format the string in the
control’s text field. The formatString property can contain any combination of "MM",
"DD", "YY", “YYYY”, delimiter, and punctuation characters. The default value is "MM/DD/
YYYY".
304 Using Controls
In the following example, you set the formatString property to "MM/DD/YY" to display a
two-digit year:
<?xml version="1.0"?>
<!-- controls\date\DateFieldFormat.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
<mx:Label text="{date2.formatString}"/>
<mx:DateField id="date2"
editable="true"
width="100"
formatString="MM/DD/YY"/>
</mx:Application>
The DateField control also lets you specify a formatter function that converts the date to a
string in your preferred format for display in the control’s text field. The DateField
labelFunction property and the DateFormatter class help you format dates.
By default, the date in the DateField control text field is formatted in the form "MM/DD/
YYYY". You use the labelFunction property of the DateField control to specify a function
to format the date displayed in the text field, and return a String containing the date. The
function has the following signature:
public function formatDate(currentDate:Date):String {
...
return dateString;
}
You can choose a different name for the function, but it must take a single argument of type
Date and return the date as a String for display in the text field. The following example
defines the function formatDate() to display the date in the form yyyy/mm/dd, such as
2005/11/24. This function uses a DateFormatter object to do the formatting.
<?xml version="1.0"?>
<!-- controls\date\DateChooserFormatter.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
private function formatDate(date:Date):String {
return dfconv.format(date);
}
]]>
</mx:Script>
<mx:DateFormatter id="dfconv" formatString="YYYY/MM/DD"/>
<mx:DateField id="df" labelFunction="formatDate" parseFunction="null"/>
</mx:Application>
DateChooser and DateField controls 305
The parseFunction property specifies a function that parses the date entered as text in the
text field of the DateField control and returns a Date object to the control. If you do not allow
the user to enter a date in the text field, set the parseFunction property to null when you
set the labelFunction property.
If you want to let the user enter a date in the control’s text field, you should specify a function
to the parseFunction property that converts the text string to a Date object for use by the
DateField control. If you set the parseFunction property, it should typically perform the
reverse of the function specified to the labelFunction property.
The function specified to the parseFunction property has the following signature:
public function parseDate(valueString:String, inputFormat:String):Date {
...
return newDate
}
Where the valueString argument contains the text string entered by the user in the text
field, and the inputFormat argument contains the format of the string. For example, if you
only allow the user to enter a text sting using two characters for month, day, and year, then
pass "MM/DD/YY" to the inputFormat argument.
User interaction
The date chooser includes arrow buttons that let users move between months. Users can select
a date with the mouse by clicking the desired date.
Clicking a forward month arrow advances a month; clicking the back arrow displays the
previous month. Clicking forward a month on December, or back on January, moves to the
next (or previous) year. Clicking a date selects it. By default, the selected date is indicated by a
green background around the date and the current day is indicated by a black background
with the date in white. Clicking the currently selected date deselects it.
The following keystrokes let users navigate DateChooser and DateField control:
Key Use
Left Arrow Moves the selected date to the previous enabled day in the month.
Does not move to the previous month.
Right Arrow Moves the selected date to the next enabled day in the month. Does
not move to the next month.
Up Arrow Moves the selected date up the current day of week column to the
previous enabled day. Does not move to the previous month.
Down Arrow Moves the selected date down the current day of week column to
next enabled day. Does not move to the next month.
306 Using Controls
Key Use
Page Up Displays the calendar for the previous month.
Page Down Displays the calendar for the next month.
Home Moves the selection to the first enabled day of the month.
End Moves the selection to the last enabled day of the month.
+ Move to the next year.
- Move to the previous year.
Control+Down Arrow DateField only: open the DateChooser control.
Control+Up Arrow DateField only: close the DateChooser control.
Escape DateField only: cancel operation.
Enter DateField only: selects the date and closes the DateChooser control.
The user must select the control before using navigation keystrokes. In a DateField
N OT E
control, all listed keystrokes work only when the date chooser is displayed.
LinkButton control
The LinkButton control creates a single-line hypertext link that supports an optional icon.
You can use a LinkButton control to open a URL in a web browser.
The following example shows three LinkButton controls:
The LinkButton control has the following default properties:
Property Default value
Default size Width and height large enough for the text
Minimum size 0
Maximum size Undefined
LinkButton control 307
Creating a LinkButton control
You define a LinkButton control in MXML using the <mx:LinkButton> tag, as the following
example shows. Specify an id value if you intend to refer to a component elsewhere in your
MXML, either in another tag or in an ActionScript block.
<?xml version="1.0"?>
<!-- controls\button\LBSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox>
<mx:LinkButton label="link1"/>
<mx:LinkButton label="link2"/>
<mx:LinkButton label="link3"/>
</mx:HBox>
</mx:Application>
The following code contains a single LinkButton control that opens a URL in a web browser
window:
<?xml version="1.0"?>
<!-- controls\button\LBSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:LinkButton label="ADBE"
width="100"
click="navigateToURL(new URLRequest('http://quote.yahoo.com/
q?s=ADBE'), 'quote')"/>
</mx:Application>
This example uses the navigateToURL() method to open the URL.
The LinkButton control automatically provides visual cues when you move your mouse
pointer over or click the control. The previous code example contains no link handling logic
but does change color when you move your mouse pointer over or click a link.
308 Using Controls
The following code example contains LinkButton controls for navigating in a ViewStack
navigator container:
<?xml version="1.0"?>
<!-- controls\button\LBViewStack.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:VBox>
<!-- Put the links in an HBox container across the top. -->
<mx:HBox>
<mx:LinkButton label="Link1"
click="viewStack.selectedIndex=0;"/>
<mx:LinkButton label="Link2"
click="viewStack.selectedIndex=1;"/>
<mx:LinkButton label="Link3"
click="viewStack.selectedIndex=2;"/>
</mx:HBox>
<!-- This ViewStack container has three children. -->
<mx:ViewStack id="viewStack">
<mx:VBox width="150">
<mx:Label text="One"/>
</mx:VBox>
<mx:VBox width="150">
<mx:Label text="Two"/>
</mx:VBox>
<mx:VBox width="150">
<mx:Label text="Three"/>
</mx:VBox>
</mx:ViewStack>
</mx:VBox>
</mx:Application>
A LinkButton control’s label is centered within the bounds of the LinkButton control. You
can position the text label in relation to the icon using the labelPlacement property, which
accepts the values right, left, bottom, and top.
LinkButton control 309
LinkButton control user interaction
When a user clicks a LinkButton control, the LinkButton control dispatches a click event. If
a LinkButton control is enabled, the following happens:
■ When the user moves the mouse pointer over the LinkButton control, the LinkButton
control changes its rollover appearance.
■ When the user clicks the LinkButton control, the input focus moves to the control and
the LinkButton control displays its pressed appearance. When the user releases the mouse
button, the LinkButton control returns to its rollover appearance.
■ If the user moves the mouse pointer off the LinkButton control while pressing the mouse
button, the control’s appearance returns to its original state and the control retains input
focus.
■ If the toggle property is set to true, the state of the LinkButton control does not change
until the mouse button is released over the control.
If a LinkButton control is disabled, it appears as disabled, regardless of user interaction. In the
disabled state, the control ignores all mouse or keyboard interaction.
HSlider and VSlider controls
You can use the slider controls to select a value by moving a slider thumb between the end
points of the slider track. The current value of the slider is determined by the relative location
of the thumb between the end points of the slider, corresponding to the slider’s minimum and
maximum values.
By default, the minimum value of a slider is 0 and the maximum value is 10. The current
value of the slider can be any value in a continuous range between the minimum and
maximum values, or it can be one of a set of discrete values, depending on how you configure
the control.
310 Using Controls
About Slider controls
Flex provides two sliders: the HSlider (Horizontal Slider) control, which creates a horizontal
slider, and the VSlider (Vertical Slider) control, which creates a vertical slider. The following
example shows the HSlider and VSlider controls:
Label
Tick mark
HSlider control Track
Thumb
HSlider control
with data tip
VSlider control
This example includes the data tip, slider thumb, track, tick marks, and labels. You can
optionally show or hide data tips, tick marks, and labels.
The following code example reproduces this image (without annotations):
<?xml version="1.0"?>
<!-- controls\slider\HSliderSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox>
<mx:VBox>
<mx:HSlider
tickInterval="2"
labels="['min', 'max']" height="150"/>
<mx:HSlider/>
</mx:VBox>
<mx:VSlider
tickInterval="2"
labels="['min', 'max']"/>
</mx:HBox>
</mx:Application>
HSlider and VSlider controls 311
The HSlider and VSlider controls have the following default properties:
Property Default value
Default size Horizontal Slider 250 pixels wide, and high enough to hold the slider and
any associated labels
Vertical Slider 250 pixels high, and wide enough to hold the slider and any
associated labels
Minimum size None
Maximum None
size
Creating a Slider control
You define an HSlider control in MXML using the <mx:HSlider> tag and a VSlider control
using the <mx:VSlider> tag. You must specify an id value if you intend to refer to a
component elsewhere, either in another tag or in an ActionScript block.
The following code example creates four HSlider controls:
■ The first slider has a maximum value of 100, and lets the user move the slider thumb to
select a value in the continuous range between 0 and 100.
■ The second slider uses the snapInterval property to define the discrete values between
the minimum and maximum that the user can select. In this example, the snapInterval
is 5, which means that the user can select the values 0, 5, 10, 15, and so on.
■ The third slider uses the tickInterval property to add tick marks and set the interval
between the tick marks to 25, so that Flex displays a tick mark along the slider
corresponding to the values 0, 25, 50, 75, and 100. Flex displays tick marks whenever you
set the tickInterval property to a nonzero value.
312 Using Controls
■ The fourth slider uses the labels property to add labels and set them at each tick mark.
The labels property accepts an array of values to display. It automatically distributes them
evenly along the slider. The first value always corresponds to the leftmost edge of the slider
and the last value always corresponds to the rightmost edge of the slider.
<?xml version="1.0"?>
<!-- controls\slider\HSliderSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:VBox>
<mx:HSlider
maximum="100"/>
<mx:HSlider
maximum="100"
snapInterval="5"/>
<mx:HSlider
maximum="100"
snapInterval="5"
tickInterval="25"/>
<mx:HSlider
maximum="100"
snapInterval="5"
tickInterval="25"
labels="[0,25,50,75,100]"/>
</mx:VBox>
</mx:Application>
This example produces the following image:
HSlider and VSlider controls 313
You can do a similar thing by using VSlider controls:
<?xml version="1.0"?>
<!-- controls\slider\VSliderSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox>
<mx:VSlider
maximum="100"/>
<mx:VSlider
maximum="100"
snapInterval="5"/>
<mx:VSlider
maximum="100"
snapInterval="5"
tickInterval="25"/>
<mx:VSlider
maximum="100"
snapInterval="5"
tickInterval="25"
labels="[0,25,50,75,100]"/>
</mx:HBox>
</mx:Application>
This code results in the following application:
You can bind the value property of a slider to another control to display the current value of
the slider. The following example binds the value property to a Text control:
<?xml version="1.0"?>
<!-- controls\slider\HSliderBinding.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HSlider id="mySlider" maximum="100"/>
<mx:Text text="{mySlider.value}"/>
</mx:Application>
314 Using Controls
This code produces the following image:
Using slider events
The slider controls let the user select a value by moving the slider thumb between the
minimum and maximum values of the slider. You use an event with the slider to recognize
when the user has moved the thumb, and to determine the current value associated with the
slider.
The slider controls can dispatch the events described in the following table:
Event Description
change Dispatches when the user moves the thumb. If the liveDragging property is
true, the event is dispatched continuously as the user moves the thumb. If
liveDragging is false, the event is dispatched when the user releases the
slider thumb.
thumbDrag Dispatches when the user moves a thumb.
thumbPress Dispatches when the user selects a thumb using the mouse pointer.
thumbRelease Dispatches when the user releases the mouse pointer after a thumbPress
event occurs.
HSlider and VSlider controls 315
The following code example uses a change event to show the current value of the slider in a
TextArea control when the user releases the slider thumb:
<?xml version="1.0"?>
<!-- controls\slider\HSliderEvent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.events.SliderEvent;
import mx.controls.sliderClasses.Slider;
private function sliderChange(event:SliderEvent):void {
var currentSlider:Slider=Slider(event.currentTarget);
thumb.text=String(currentSlider.value);
}
]]>
</mx:Script>
<mx:HSlider change="sliderChange(event);"/>
<mx:TextArea id="thumb"/>
</mx:Application>
By default, the liveDragging property of the slider control is set to false, which means that
the control dispatches the change event when the user releases the slider thumb. If you set
liveDragging to true, the control dispatches the change event continuously as the user
moves the thumb, as the following example shows:
<?xml version="1.0"?>
<!-- controls\slider\HSliderEventLiveDrag.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.events.SliderEvent;
import mx.controls.sliderClasses.Slider;
private function sliderChangeLive(event:SliderEvent):void {
var currentSlider:Slider=Slider(event.currentTarget);
thumbLive.text=String(currentSlider.value);
}
]]>
</mx:Script>
<mx:HSlider
liveDragging="true"
change="sliderChangeLive(event);"/>
<mx:TextArea id="thumbLive"/>
</mx:Application>
316 Using Controls
Using multiple thumbs
You can configure a slider control to have one thumb, or two thumbs. If you configure the
slider to use a single thumb, you can move the thumb anywhere between the end points of the
slider. If you configure it to have two thumbs, you cannot drag one thumb across the other
thumb.
When you configure a slider control to have two thumbs, you use the values property of the
control to access the current value of each thumb. The values property is a two-element array
that contains the current value of the thumbs, as the following example shows:
<?xml version="1.0"?>
<!-- controls\slider\HSliderMultThumb.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.events.SliderEvent;
import mx.controls.sliderClasses.Slider;
private function sliderChangeTwo(event:SliderEvent):void {
var ct:Slider=Slider(event.currentTarget);
thumbTwoA.text=String(ct.values[0]);
thumbTwoB.text=String(ct.values[1]);
thumbIndex.text=String(event.thumbIndex);
}
]]>
</mx:Script>
<mx:HSlider thumbCount="2"
change="sliderChangeTwo(event);"/>
<mx:TextArea id="thumbTwoA"/>
<mx:TextArea id="thumbTwoB"/>
<mx:TextArea id="thumbIndex"/>
</mx:Application>
This example also uses the thumbIndex property of the event object. This property has a value
of 0 if the user modified the position of the first thumb, and a value of 1 if the user modified
the position of the second thumb.
Using data tips
By default, when you select a slider thumb, a data tip appears, showing the current value of
the slider. As you move the selected thumb, the data tip shows the new slider value. You can
disable data tips by setting the showDataTip property to false.
HSlider and VSlider controls 317
You can use the dataTipFormatFunction property to specify a callback function to format
the data tip text. This function takes a single String argument containing the data tip text, and
returns a String containing the new data tip text, as the following example shows:
<?xml version="1.0"?>
<!-- controls\slider\HSliderDataTip -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
private function myDataTipFunc(val:String):String {
return "Current value: " + String(val);
}
]]>
</mx:Script>
<mx:HSlider
height="80"
dataTipFormatFunction="myDataTipFunc"/>
</mx:Application>
This code produces the following image:
In this example, the data tip function prepends the data tip text with the String
"Current value: ". You can modify this example to insert a dollar sign ($) prefix on the data tip
for a slider that controls the price of an item.
Keyboard navigation
The HSlider and VSlider controls have the following keyboard navigation features when the
slider control has focus:
Key Description
Left Arrow Decrement the value of an HSlider control by 1 snap interval or, if you do not
specify a snap interval, by 1 pixel.
Right Arrow Increment the value of a HSlider control by 1 snap interval or, if you do not
specify a snap interval, by 1 pixel.
Home Moves the thumb of an HSlider control to its minimum value.
End Moves the thumb of an HSlider control to its maximum value.
318 Using Controls
Key Description
Up Arrow Increment the value of an VSlider control by 1 snap interval or, if you do not
specify a snap interval, by 1 pixel.
Down Arrow Decrement the value of a VSlider control by 1 snap interval or, if you do not
specify a snap interval, by 1 pixel.
Page Down Moves the thumb of a VSlider control to its minimum value.
Page Up Moves the thumb of a VSlider control to its maximum value.
SWFLoader control
The SWFLoader control lets you load one Flex 2 application into another Flex application. It
has properties that let you scale its contents. It can also resize itself to fit the size of its
contents. By default, content is scaled to fit the size of the SWFLoader control. The
SWFLoader control can also load content on demand programmatically, and monitor the
progress of a load operation.
The SWFLoader control also lets you load the contents of a GIF, JPEG, PNG, SVG, or SWF
file into your application, where the SWF file does not contain a Flex 2 application.
Flex also includes the Image control for loading GIF, JPEG, PNG, SVG, or SWF files.
NO TE
You typically use the Image control for loading static graphic files and SWF files, and use
the SWFLoader control for loading Flex 2 applications as SWF files. The Image control
is also d