Developing Flex Applications

Developing Flex Applications
Flex 2 Developer’sGuide
®
™
Adobe Flex 2
© 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 APPLICATIONS
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 . . . . . . . . . . . . . . . . . . . .
Using inline styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Loading style sheets at run time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using filters in Flex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About themes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
737
742
744
753
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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About RPC services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About the Data Management Service . . . . . . . . . . . . . . . . . . . . . . . . .
About messaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using Flex Data Services with Flex Builder . . . . . . . . . . . . . . . . . . . .
1345
1346
1348
1349
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 operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using the charting controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About the axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About charting events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Creating charts in ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Defining chart data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1573
1575
1583
1584
1585
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
Languages”
Describes how to use MXML and ActionScript.
Part 2, “Building User Interfaces
for Flex Applications”
Describes how to use Flex components to build the user
interface to your application.
Part 3, “Customizing the User
Interface”
Describes how to improve the user experience by adding
additional functionality to your application.
Part 4, “Flex Programming
Topics”
Describes some advanced programming techniques that
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
Interconnectivity”
Describes the Flex features that let you work with
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
Applications
Describes how to build and deploy Flex applications.
Creating and Extending Flex 2
Components
Describes how to create and extend Flex 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
1
Using Flex Programming
Languages
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
2
Developing Applications
in MXML
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
■
HTTPService
■
RemoteObject provides access to Java objects using the AMF protocol (Flex Data Services
provides access to SOAP-based web services
provides access to HTTP URLs that return data
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 userinterface 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.
N O TE
You cannot access custom MXML component URLs directly in a web browser.
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.
N OT E
Do not use the backslash character (\) as a separator in the path to an application asset.
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 &#13; code in your String value in MXML
■
By inserting "\n" in an ActionScript String variable used to initialize the MXML property
To use the &#13; 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&#13;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.
NO T E
You specify a script in the source property of an <mx:Script> tag. You do not specify
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
flags
Specifies the regular expression within the two slashes. Both slashes are required.
(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
attribute:
source
■
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 " + [email protected] + "=" + button1[[email protected]] +
" (" + [email protected] + ")\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 ([email protected] == 'writeonly') {
ta1.text += "Property " + [email protected] + " (" + [email protected] +")\n";
}
else {
ta1.text += "Property " + [email protected] + "=" +
button1[[email protected]] + " (" + [email protected] +")\n";
}
}
// List the object's methods.
for each (var m:XML in classInfo..method) {
ta1.text += "Method " + [email protected] + "():" + [email protected] +
"\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 eventspecific 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:
■
■
116
stopPropagation()
stopImmediatePropagation()
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/DOMLevel-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
2
Building User Interfaces for
Flex Applications
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
6
Using Flex Visual
Components
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:
NO T E
Although you can specify multiple lines of ActionScript code, separated by semicolons,
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).
NO T E
For more information on how components are created, see “About the component
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:
Readwrite
property
MXML example
ActionScript example
<mx:Tile id="tile1"
label="My Tile"
visible="true"/>
tile1.label="My Tile";
tile1.visible=true;
Read-only You cannot use a read-only
property
property as an attribute in MXML.
To get the value of a read-only property:
Method
Methods are not available in
MXML.
myList.sortItemsBy("data", "DESC");
Event
<mx:Accordion id="myAcc"
change="changeHandler
(event);"/>
private function
changeHandler(event:MouseEvent):void {
...
}
var theClass:String=mp1.className;
(You must also define a
changeHandler() function as shown myButton.addEventListener("click",
changeHandler);
in the ActionScript example.
Style
<mx:Tile id="tile1"
paddingTop="12"
paddingBottom="12"/>
To set the style:
tile1.setStyle("paddingTop", 12);
tile1.setStyle("paddingBottom", 12);
To get the style:
var currentPaddingTop:Number =
tile1.getStyle("paddingTop");.
Behavior
<mx:Tile id="tile1"
showEffect="{AWipeEffect}"/>
To set the behavior:
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:
4.
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.
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:
■
150
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.
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:
and y
■
x
■
width
■
styles, by using setStyle(stylename, value)
and height
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.
N OT E
The stored values of width and height are always in pixels regardless of whether the
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.
■
158
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.
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
7
Using Data Providers
and Collections
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 providerbased 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.
NO T E
When Flex creates a UID for an object, such as an item in an ArrayCollection, it adds the
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 uniquelyidentifying 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
public var
public var
public var
Person implements IUID {
employee_id:String;
firstName:String;
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;
}
}
}
NO TE
Object cloning does not manage or have a relationship with UIDs, so if you clone
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.
NO T E
If you use a raw object, such as an Array, as a control’s data provider, Flex automatically
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 arraybased 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.
NO T E
If you use the ICollectionView interface to sort or filter a collection, do not use the IList
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
// and
public
//
function to change the collection,
therefore the Array.
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
public function
collectionEventHandler(event:CollectionEvent):void {
switch(event.kind) {
case CollectionEventKind.ADD:
addLog("Item "+ event.location +
break;
case CollectionEventKind.REMOVE:
addLog("Item "+ event.location +
break;
case CollectionEventKind.REPLACE:
addLog("Item "+ event.location +
break;
case CollectionEventKind.UPDATE:
addLog("Item updated");
break;
}
}
// Helper function for adding information to
public function addLog(str:String):void {
log.text += str + "\n";
}
in the TextArea).
" added");
" removed");
" Replaced");
the log.
// 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
IMenuDataDescriptor
Methods used by Tree controls
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/
Method
Returns
DefaultDataDescriptor behavior
Both
hasChildrent(node,
[model])
Boolean value
indicating whether
the node a branch
with children.
For XML, returns true if the node has at least one
child element.
For other objects, returns true if the node has a
non-empty children field.
Both
getChildren(node,
[collection])
A node’s children. For XML, returns an XMLListCollection with the
child elements.
For other Objects, returns the contents of the
node’s children field.
Both
isBranch(node,
[collection])
Whether a node is For XML, returns true if the node has at least one
a branch.
child, or if it has an isBranch attribute.
For other Objects, returns true if the node has an
isBranch field.
Both
getData(node,
[collection])
The node data.
Both
addChildAt(node,
child, index, [model])
Boolean value
For all cases, inserts the node as a child object
indicating whether before the node currently in the index location.
the operation
succeeded.
Returns the node.
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/
Method
Returns
DefaultDataDescriptor behavior
IMenuDataDescriptor A String with the
getType(node)
menu node type,
Meaningful values
are check, radio,
and separator.
For XML, returns the value of the type attribute of
the node.
For other Objects, returns the contents of the
node’s type field.
IMenuDataDescriptor Boolean value
isEnabled(node)
indicating if a
menu node is
enabled.
For XML, returns the value of the enabled attribute
of the node.
For other Objects, returns the contents of the
node’s enabled field.
IMenuDataDescriptor
setEnabled(node,
value)
For XML, sets the value of the enabled attribute of
the node to true or false.
For other Objects, sets the contents of the node’s
enabled field.
IMenuDataDescriptor Boolean value
isToggled(node)
indicating if a
menu node is
selected
For XML, returns the value of the selected
attribute of the node.
For other Objects, returns the contents of the
node’s enabled field.
IMenuDataDescriptor
setToggled(node,
value)
For XML, sets the value of the selected attribute
of the node to true or false.
For other Objects, sets the contents of the node’s
enabled field.
IMenuDataDescriptor The name of the
radio button group
getGroupName
to which the node
(node)
belongs.
For XML, returns the value of the groupName
attribute of the node.
For other Objects, returns the contents of the
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 wellformed 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
8
Sizing and Positioning
Components
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 0pixel 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.
N OT E
Flex coordinates increase from the upper left corner of the frame of reference. Thus, an
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
positioning: Canvas,
container or
Application or Panel
container with
General layout: Children of the container do not interact. That is,
children can overlap and the position of one child does not affect the
position of any other child. You specify the child positions explicitly or
use constraints to anchor the sides or centers of the children relative to
the parent container.
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.
layout="absolute"
Controls that
arrange all children
linearly, such as
Box, HBox, VBox
General layout: All children of the container are arranged in a single
row or column. Each child’s height and width can differ from all other
children’s heights or widths.
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:
ViewStack,
Accordion,
TabNavigator
General layout: The container displays one child at a time.
Default sizing: The container size is determined by the measured or
explicit dimensions of the initially selected child, and thereafter, all
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
properties
Description
Actual
dimensions
Returned by the height
and width properties.
The height and width of the displayed control,
in pixels, as determined by the layout phase.
If you set any explicit values, they determine
the corresponding actual values.
Explicit
dimensions
explicitHeight,
A dimension that you specifically set as a
number of pixels. These dimensions cannot be
overridden.
Setting the height and
Application developers typically use the height
width properties to
integer values also sets
and width properties to set explicit dimensions.
You cannot have both an explicit dimension
the explicitHeight and
explicitWidth properties. and a percentage-based dimension, setting
one unsets the other.
explicitWidth
Sizing components
229
Characteristic Associated
properties
Description
Percentagebased
dimensions
A dimension that you specifically set as a
number in the range 0-100, as a percentage of
the viewable area of the parent container.
In MXML tags only,
If you set a percentage-based dimension, the
setting the height and
component is resizable, and grows or shrinks if
width properties to
percentage string values, the parent dimension changes.
such as “50%” also sets
the percentHeight and
percentWidth properties.
Default
dimensions
measuredHeight,
percentHeight,
percentWidth
measuredWidth
Not used directly by application developers.
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 percentagebased 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
Properties
Minimum
dimensions
230
Description
The minimum dimensions a component can
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.
minHeight, minWidth
Sizing and Positioning Components
Characteristic Associated
Properties
Description
Maximum
dimensions
The maximum dimensions a component can
have.
The default values of these properties are
component-specific, but often are 10000
pixels.
Minimum default
dimensions
maxHeight, maxWidth
Setting the explicit
maximum dimensions
also sets the maxHeight
and maxWidth properties.
measuredMinHeight,
measuredMinWidth
Not used by application developers.
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.
N OT E
For a summary of the basic rules for component sizing, see “Basic layout rules and
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.
NO TE
Setting a component’s includeInLayout property to false does not prevent Flex from
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 percentagebased 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}
Button3: {bG3.width}
</mx:text>
</mx:TextArea>
</mx:Application>
234
Sizing and Positioning Components
Button2: {bG2.width}
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 1pixel-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}
Button3: {bG3.width}
</mx:text>
</mx:TextArea>
</mx:Application>
Button2: {bG2.width}
For more information and examples showing sizing of containers and children, see “Using
Flex component sizing techniques” on page 236. For detailed information on percentagebased 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
properties to 100%. That way, the Flex application scales to fit the space that is
allocated to the Flash plug-in.
height
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:
N OT E
254
If you use percentage-based sizing for the children of a control that uses absolute
positioning, be aware that percentage-based components resize when the parent
container resizes, and the result may include unwanted overlapping of controls.
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.
NO TE
For an introduction to using constraint-based layout in Flex Builder, see Getting Started
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
value is true (checked) or false
(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
swatch panel (palette).
“DateChooser and DateField
controls” on page 296
DataGrid
Displays data in a tabular format.
“DataGrid control” on page 467
“CheckBox control”
on page 287
About controls
263
Control
Description
For more information
DateChooser
Displays a full month of days to let you
select a date.
“DateChooser and DateField
controls” on page 296
DateField
Displays the date with a calendar icon
on its right side. When a user clicks
anywhere inside the control, a
DateChooser control pops up and
displays a month of dates.
“DateChooser and DateField
controls” on page 296
HorizontalList
Displays a horizontal list of items.
“HorizontalList control”
on page 450
HRule/VRule
Displays a single horizontal rule
(HRule) or vertical rule (VRule).
“HRule and VRule controls”
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
SWF files.
“Image control” on page 325
Label
Displays a noneditable single-line field
label.
“LinkButton control”
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
contains one or more submenus of
Menu controls.
“MenuBar control” on page 431
NumericStepper
Displays a dual button control that you
can use to increase or decrease the
value of the underlying variable.
“NumericStepper control”
on page 294
ProgressBar
Provides visual feedback of how much
time remains in the current operation.
“ProgressBar control”
on page 356
264
Using Controls
Control
Description
For more information
RadioButton
Displays a set of buttons of which
exactly one is selected at any time.
“RadioButton control”
on page 288
RadioButton
Group
Displays a group of RadioButton
controls with a single click event
listener.
“Creating a group using the
<mx:RadioButtonGroup> tag”
on page 292
RichTextEditor
Includes a multiline editable text field
and controls for specifying text
formatting.
“RichTextEditor control”
on page 398
ScrollBar
(HScrollBar and
VScrollBar)
Displays horizontal and vertical scroll
bars.
“ScrollBar control” on page 365
SWFLoader
Displays the contents of a specified
SWF file or JPEG file.
“SWFLoader control”
on page 319
TabBar
Displays a horizontal row of tabs.
“TabBar control” on page 283
Text
Displays a noneditable multiline text
field.
“TextInput control” on page 393
TextArea
Displays an editable text field for user
input that can accept more than a
single line of input.
“Using Text Controls”
on page 369
TextInput
Displays an editable text field for a
single line of user input. Can contain
alphanumeric data, but input is
interpreted as a String data type.
“TextInput control” on page 393
TileList
Displays a tiled list of items. The items
are tiled in vertical columns or
horizontal rows.
“TileList control” on page 454
ToggleButtonBar Displays a row of related buttons with a “ButtonBar and
common appearance.
ToggleButtonBar controls”
on page 276
Tree
Displays hierarchical data arranged as
an expandable tree.
“Tree control” on page 479
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;"/>
NO T E
The preceding technique works even if the width property was originally set as a
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.
N OT E
You cannot use the Tab key to leave an opened pop-up control; you must make a
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
■
index
String containing the label of the selected tab.
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.
NO TE
The code that determines the value of the wholeDate field adds 1 to the month number
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 16pixel 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.
N OT E
The user must select the control before using navigation keystrokes. In a DateField
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
size
None
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.
NO TE
Flex also includes the Image control for loading GIF, JPEG, PNG, SVG, or SWF files.
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 designed to be used in custom cell renderers and item editors.
For more information on the Image control, see “Image control” on page 325. For more
information on using the SWFLoader control to load a Flex application, see “Using the
SWFLoader control to load a Flex Data Services application” on page 323.
A SWFLoader control cannot receive focus. However, content loaded into the SWFLoader
control can accept focus and have its own focus interactions.
The SWFLoader control has the following default properties:
Property
Default value
Default size
Width and height large enough for the loaded content
Minimum size
0
Maximum size
Undefined
SWFLoader control
319
Creating a SWFLoader control
You define a SWFLoader control in MXML using the <mx:SWFLoader> 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\swfloader\SWFLoaderSimple.mxml-->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:SWFLoader id="loader1" source="FlexApp.swf"/>
</mx:Application>
Like the Image control, you can also use the Embed statement with the SWFLoader control
to embed the image in your application, as the following example shows:
<?xml version="1.0"?>
<!-- controls\swfloader\SWFLoaderSimpleEmbed.mxml-->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:SWFLoader id="loader1" source="@Embed(source='flexapp.swf')"/>
</mx:Application>
When using the SWFLoader control with an SVG file, you can only load it using an Embed
statement; you cannot load an SVG file at run time. For more information about embedding
resources, see the description for the Image control at “About importing images” on page 325,
and Chapter 30, “Embedding Assets,” on page 1113.
This technique works well with SWF files that add graphics or animations to an application,
but are not intended to have a large amount of user interaction. If you import SWF files that
require a large amount of user interaction, you should build them as custom components. For
more information on custom components, see Creating and Extending Flex 2 Components.
320
Using Controls
Interacting with a loaded Flex 2 application
The following example, in the file FlexApp.mxml, shows a simple Flex application that
defines two Label controls, a variable, and a method to modify the variable:
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
height="200" width="200">
<mx:Script>
<![CDATA[
[Bindable]
public var varOne:String = "This is a public variable";
public function setVarOne(newText:String):void {
varOne=newText;
}
]]>
</mx:Script>
<mx:Label id="lblOne" text="I am here"/>
<mx:Label text="{varOne}"/>
<mx:Button label="Nested Button" click="setVarOne('Nested button
pressed.');"/>
</mx:Application>
SWFLoader control
321
You compile this example into the file FlexApp.SWF, and then use the SWFLoader control to
load it into another Flex application, as the following example shows:
<?xml version="1.0"?>
<!-- controls\swfloader\SWFLoaderInteract.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.managers.SystemManager;
import mx.controls.Label;
[Bindable]
public var loadedSM:SystemManager;
// Initialize variables with information from
// the loaded application.
private function initNestedAppProps():void {
loadedSM = SystemManager(myLoader.content);
}
// Update the Label control in the outer application
// from the Label control in the loaded application.
public function updateLabel():void {
lbl.text=loadedSM.application["lblOne"].text;
}
// Write to the Label control in the loaded application.
public function updateNestedLabels():void {
loadedSM.application["lblOne"].text = "I was just updated";
loadedSM.application["varOne"] = "I was just updated";
}
// Write to the varOne variable in the loaded application
// using the setVarOne() method of the loaded application.
public function updateNestedVarOne():void {
FlexApp(loadedSM.application).setVarOne("Updated varOne!");
}
]]>
</mx:Script>
<mx:Label id="lbl"/>
<mx:SWFLoader id="myLoader" width="300"
source="FlexApp.swf"
creationComplete="initNestedAppProps();"/>
<mx:Button label="Update Label Control in Outer Application"
click="updateLabel();"/>
<mx:Button label="Update Nested Controls"
322
Using Controls
click="updateNestedLabels();"/>
<mx:Button label="Update Nexted varOne"
click="updateNestedVarOne();"/>
</mx:Application>
Notice that this application loads the SWF file at run time, it does not embed it. For
information on embedding a Flex 2 application using the SWFLoader tag, see Chapter 30,
“Embedding Assets,” on page 1113.
In the preceding example, you use the creationComplete event of the SWFLoader control to
initialize two variables; the first contains a reference to the SystemManager object for the
loaded Flex application, and the second contains a reference to the Label control in the loaded
application.
When a user clicks the first Button control in the outer application, Flex copies the text from
the Label control in the loaded application to the Label control in the outer application.
When a user clicks the second Button control, Flex writes the text to the Label control and to
the varOne variable defined in the loaded application.
When a user clicks the third Button control, Flex uses the setVarOne() method of the loaded
application to write to the varOne variable defined in the loaded application.
Using the SWFLoader control to load a Flex Data
Services application
Flex Data Services users can use the SWFLoader control to load a Flex application. The
following code example loads the file buttonicon.mxml, where buttonicon.mxml is the
example found in “Embedding an icon in a Button control” on page 270:
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:SWFLoader source="buttonicon.mxml.swf" scaleContent="false"/>
</mx:Application>
In this example, you specify the value of the source property as "buttonicon.mxml.swf".
Adobe Flex Data Services compiles the file buttonicon.mxml, and returns the SWF file to the
main application. If you had specified the value as "buttonicon.swf", Flex Data Services
returns the SWF file if it exists, but will not compile buttonicon.mxml if it does not.
SWFLoader control
323
Externalizing application classes
To reduce the size of the applications that you load using the SWFLoader control, you can
instruct the loaded application to externalize framework classes that are also included by the
loading application. The result is that the loaded application is smaller because it only
includes the classes it requires, while the framework code and other dependencies are included
in the loading application.
To externalize framework classes, you generate a linker report from the loading application by
using link-report option to the mxmlc command. You then use the load-externs option
to the mxmlc compiler to specify this report when you compile the loaded application.
To externalize framework classes:
1.
Generate the linker report for the loading application:
mxmlc -link-report=report.xml MyApplication.mxml
2.
Compile the loaded application using the link report:
mxmlc -load-externs=report.xml MyLoadedApplication.mxml
3.
Compile the loading application:
mxmlc MyApplication.mxml
NO TE
If you externalize the loaded application’s dependencies by using the load-externs
option, your loaded application might not be compatible with future versions of Adobe
Flex. Therefore, you might be required to recompile the application. To ensure that a
future Flex application can load you application, compile that module with all the classes
it requires.
For more information, see Chapter 9, “Using the Flex Compilers,” in Building and Deploying
Flex 2 Applications.
Sizing a SWFLoader control
You use the SWFLoader control’s scaleContent property to control the sizing behavior of
the SWFLoader control. When the scaleContent property is set to true, Flex scales the
content to fit within the bounds of the control. However, images will still retain their aspect
ratio by default.
324
Using Controls
Image control
Adobe Flex supports several image formats, including GIF, JPEG, PNG, SVG, and SWF files.
You can import these images into your applications by using the Image control.
NO TE
Flex also includes the SWFLoader control for loading Flex 2 applications. You typically
use the Image control for loading static graphic files and SWF files, and use the
SWFLoader control for loading Flex 2 applications. The Image control is also designed
to be used in custom item renderers and item editors. For more information on the
SWFLoader control, see “SWFLoader control” on page 319.
About importing images
Flex supports importing GIF, JPEG, PNG, and SWF files at run time, and embedding GIF,
JPEG, PNG, SVG, and SWF at compile time. The method you choose depends on the file
types of your images and your application parameters.
Embedded images load immediately, because they are already part of the Flex SWF file.
However, they add to the size of your application and slow down the application initialization
process. Embedded images also require you to recompile your applications whenever your
image files change. For an overview of resource embedding, see Chapter 30, “Embedding
Assets,” on page 1113.
The alternative to embedding a resource is to load the resource at run time. You can load a
resource from the local file system in which the SWF file runs, or you can access a remote
resource, typically though an HTTP request over a network. These images are independent of
your Flex application, so you can change them without causing a recompile operation as long
as the names of the modified images remain the same. The referenced images add no
additional overhead to an application’s initial loading time. However, you might experience a
delay when you use the images and load them into Adobe Flash Player.
A SWF file can access one type of external resource only, either local or over a network; it
cannot access both types. You determine the type of access allowed by the SWF file using the
use-network flag when you compile your application. When use-network flag is set to
false, you can access resources in the local filesystem, but not over the network. The default
value is true, which allows you to access resources over the network, but not in the local
filesystem.
For more information on the use-network flag, see Chapter 9, “Using the Flex Compilers,”
in Building and Deploying Flex 2 Applications.
Image control
325
When you load images at run time, you should be aware of the security restrictions of Flash
Player. For example, you can reference an image by using a URL, but the default security
settings only permit Flex applications to access resources stored on the same domain as your
application. To access images on other servers, you must use a crossdomain.xml file.
For more information on application security, see Chapter 4, “Applying Flex Security,” in
Building and Deploying Flex 2 Applications.
SVG drawing restrictions
You should be aware of the following restrictions when working with SVG files in Flex:
■
You can only embed an SVG file in an application; you cannot load one at run time
■
SMIL and animation are not supported
■
Masking and filters are not supported
■
Pattern Fill and some advanced Gradients are not supported
■
Interactivity and scripting is not supported
■
SVG text is rendered as nonsearchable and nonselectable SWF shape outlines, meaning it
is not rendered as native text in Flash Player
Controlling image importing with the Image control
The Image control supports the following actions when you import an image:
■
Specifying the image path
■
Sizing an image
■
Positioning the image in a Canvas container
■
Setting visibility
Specifying the image path
The value of the source property of an Image control specifies a relative or absolute path, or
URL to the imported image file. If the value is relative, it is relative to the directory that
contains the file that uses the tag. For more examples, see “Specifying the image path”
on page 326.
The source property has the following forms:
■
source="@Embed(source='relativeOrAbsolutePath')"
326
Using Controls
The referenced image is packaged within the generated SWF file at compile-time when
Flex creates the SWF file for your application. You can embed GIF, JPEG, PNG, SVG,
and SWF files. When you embed an image, the value of the source property must be a
relative or absolute path to a file on your local file system; it cannot be a URL.
The following example embeds a JPEG image into a Flex application:
<?xml version="1.0"?>
<!-- controls\image\ImageSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Image id="loader1" source="@Embed(source='logo.jpg')"/>
</mx:Application>
In this example, the size of the image is the default size of the image file.
■
source="relativeOrAbsolutePathOrURL"
Flex loads the referenced image file at run time; it is not packaged as part of the generated
SWF file. You can only reference GIF, JPEG, PNG, and SWF files. When use-network
flag is set to false, you can access resources in the local filesystem, but not over the
network. The default value is true, which allows you to access resources over the network,
but not in the local filesystem.
The following example access a JPEG image at run time:
<?xml version="1.0"?>
<!-- controls\image\ImageSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Image id="loader1" source="logo.jpg"/>
</mx:Application>
Because you did not use @Embed in the source property, Flex
loads the image at run time.
In many applications, you create a directory to hold your application images. Commonly, that
directory is a subdirectory of your main application directory. The source property supports
relative paths to images, which lets you specify the location of an image file relative to your
application directory.
The following example stores all images in an assets subdirectory of the application directory:
<?xml version="1.0"?>
<!-- controls\image\ImageSimpleAssetsDir.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Image id="loader1" source="@Embed(source='assets/logo.jpg')"/>
</mx:Application>
Image control
327
The following example uses a relative path to reference an image in an assets directory at the
same level as the application’s root directory:
<?xml version="1.0"?>
<!-- controls\image\ImageSimpleAssetsDirTop.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Image id="loader1" source="@Embed(source='../assets/logo.jpg')"/>
</mx:Application>
You can also reference an image using a URL, but the default security settings only permit
Flex applications to access resources stored on the same domain as your application. To access
images on other servers, you must use a crossdomain.xml file.
The following example shows how to reference an image using a URL:
<?xml version="1.0"?>
<!-- controls\image\ImageSimpleAssetsURL.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Image id="image1"
source="http://localhost:8100/flex/assets/logo.jpg"/>
</mx:Application>
N OT E
You can use relative URLs for images hosted on the same web server as the Flex
application, but you must load these images over the Internet rather than access them
locally.
Using an image multiple times
You can use the same image multiple times in your application by using the normal image
import syntax each time. Flex only loads the image once, and then references the loaded
image as many times as necessary.
Sizing an image
Flex sets the height and width of an imported image to the height and width settings in the
image file. By default, Flex does not resize the image.
To set an explicit height or width for an imported image, set its height and width properties
of the Image control. Setting the height or width property prevents the parent from resizing
it. The scaleContent property has a default value of true, therefore, Flex scales the image as
it resizes it to fit the specified height and width. The aspect ratio is maintained by default, so
the image may not completely fill the designated space. Set the scaleContent property to
false to disable scaling. Set the maintainAspectRatio property to false to allow an image
to fill all available space regardless of its dimensions. For more information about image aspect
ratios, see “Maintaining aspect ratio when sizing” on page 329.
328
Using Controls
To let Flex resize the image as part of laying out your application, set the height or width
properties to a percentage value. Flex attempts to resize components with percentage values
for these properties to the specified percentage of their parent container. You can also use the
maxHeight and maxWidth and minHeight and minWidth properties to limit resizing. For
more information on resizing, see Chapter 13, “Introducing Containers,” on page 491.
One common use for resizing an image is to create image thumbnails. In the following
example, the image has an original height and width of 100 by 100 pixels. By specifying a
height and width of 20 by 20 pixels, you create a thumbnail of the image.
<?xml version="1.0"?>
<!-- controls\image\ImageSimpleThumbnail.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Image id="image1"
source="logo.jpg"
width="20" height="20"/>
<mx:Image id="image2"
source="logo.jpg"/>
</mx:Application>
Maintaining aspect ratio when sizing
The aspect ratio of an image is the ratio of its width to its height. For example, a standard
NTSC television set uses an aspect ratio of 4:3, and an HDTV set uses an aspect ratio of 16:9.
A computer monitor with a resolution of 640 by 480 pixels also has an aspect ratio of 4:3. A
square has an aspect ratio of 1:1.
All images have an inherent aspect ratio. When you use the height and width properties of
the Image control to resize an image, by default Flex preserves the aspect ratio of the image so
that it does not appear distorted.
By preserving the aspect ratio of the image, Flex might not draw the image to fill the entire
height and width specified for the <mx:Image> tag. For example, if your original image is a
square 100 by 100 pixels, which means it has an aspect ratio of 1:1, and you use the following
statement to load the image:
<mx:Image source="myImage.jpg" height="200" width="200"/>
The image increase to four times its original size and fills the entire 200 x 200 pixel area.
The following example sets the height and width of the same image to 150 by 200 pixels, an
aspect ratio of 3:4:
<mx:Image source="myImage.jpg" height="150" width="200"/>
Image control
329
In this example, you do not specify a square area for the resized image. Flex maintains the
aspect ratio of an image by default, therefore, Flex sizes the image to 150 by 150 pixels, the
largest possible image that maintains the aspect ratio and conforms to the size constraints.
The other 50 by 150 pixels remain empty. However, the <mx:Image> tag reserves the empty
pixels and makes them unavailable to other controls and layout elements.
You can use a Resize effect to change the width and height of an image in response to a trigger.
As part of configuring the Resize effect, you specify a new height and width for the image.
Flex maintains the aspect ratio of the image by default, so it resizes the image as much as
possible to conform to the new size, while maintaining the aspect ratio. For example, place
your mouse pointer over the image in this example to enlarge it, and then move the mouse off
the image to shrink it to its original size:
<?xml version="1.0"?>
<!-- controls\image\ImageResize.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Resize id="resizeBig" widthFrom="120" widthTo="200"/>
<mx:Resize id="resizeSmall" widthFrom="200" widthTo="120"/>
<mx:Image width="120"
source="@Embed('logo.jpg')"
rollOverEffect="{resizeBig}"
rollOutEffect="{resizeSmall}"/>
</mx:Application>
For more information on the Resize effect, see Chapter 17, “Using Behaviors,” on page 649.
If you do not want to preserve the aspect ratio when you resize an image, you can set the
maintainAspectRatio property to false. By default, maintainAspectRatio is set to true
to enable the preservation of the aspect ratio.
The following example resizes the Flex logo to the exact values of the height and width
properties without regard for its aspect ratio:
<?xml version="1.0"?>
<!-- controls\image\ImageResizeMaintainAR.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Image id="image1"
source="@Embed('logo.jpg')"
width="250" height="100"
maintainAspectRatio="false"/>
</mx:Application>
330
Using Controls
By choosing not to maintain the aspect ratio, you allow for the possibility of a distorted
image. For example, the Adobe logo is 136 by 47 pixels by default. In the following example,
it is distorted because the aspect ratio is not maintained when the image is resized:
Positioning the image in a Canvas container
A Canvas container, and the Panel and Application containers with the layout property set to
absolute, let you specify the location of its children within the container. To specify the
absolute position of an image, you use the x and y properties of the Image control.
NO TE
In all other containers, the container controls the positioning of its children and ignores
the x and y properties.
The x and y properties specify the location of the upper-left corner of the image in the Canvas
container. In the following example, you set the position of the image at (40,40), 40 pixels
down and 40 pixels to the right of the upper-left corner of the Canvas container:
<?xml version="1.0"?>
<!-- controls\image\ImageCanvas.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Canvas id="canvas0"
borderStyle="solid"
width="200"
height="200">
<mx:Image id="img0"
source="@Embed('logo.jpg')"
x="40" y="40"/>
</mx:Canvas>
</mx:Application>
This code results in the following application:
Image control
331
Setting visibility
The visible property of the Image control lets you load an image but render it invisible. By
default, the image is visible. To make an image invisible, set the visible property to false.
The following example loads an image but does not make it visible:
<?xml version="1.0"?>
<!-- controls\image\ImageVisible.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:VBox id="vbox0"
borderStyle="solid">
<mx:Image id="img0"
visible="false"
source="@Embed(source='logo.jpg')"/>
</mx:VBox>
</mx:Application>
The VBox container still allocates space for the image when it lays out its children. Thus, the
VBox is the same size as the image file and, if your application contained a Button control
after the <mx:Image> tag, the button would appear in the same location as if the image was
visible.
If you want to make the image invisible, and have its parent container ignore the image when
sizing and positioning its other children, set the includeInLayout property of the Image
control to false. By default, the includeInLayout property to true, so that even when the
image is invisible, the container sizes and positions it as if it were visible.
Often, you use the visible property to mark all images invisible, except one image. For
example, assume that you have an area of your application dedicated to showing one of three
possible images based on some user action. You set the visible property set to true for
only one of the possible images; you set the visible property set to false for all other
images, which makes them invisible.
332
Using Controls
You can use ActionScript to set image properties. In the following example, when the user
clicks the button, the action sets the visible property of the image to true to make it
appear:
<?xml version="1.0"?>
<!-- controls\image\ImageAS.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
private function showImage():void {
image1.visible=true;
}
]]>
</mx:Script>
<mx:VBox id="vbox0"
width="80"
height="80">
<mx:Image id="image1"
visible="false"
source="@Embed(source='logo.jpg')"/>
<mx:Button id="myButton"
label="Show" click="showImage();"/>
</mx:VBox>
</mx:Application>
This following examples shows the results, before and after a user clicks the button:
If you set the visible property, you can control when images are loaded. By allocating space
but making images invisible when a page loads, you ensure that any slower performance
occurs during the initialization stage when users expect it, rather than as they interact with the
application and perform actions that require the image. By setting the visible property, you
can also prevent resizing and relayout within your application at seemingly random intervals.
Techniques for using the Image control
Often in a product catalog, when a user clicks an item, the catalog displays an image of the
item. One strategy for building a catalog is to load the catalog images into your application,
but make them all invisible. When a user selects a product, you make that image visible.
Image control
333
However, this strategy requires that you add an Image control for all the images in your
catalog and load the images, even if they are invisible, when the application starts. The
resulting SWF file would be unnecessarily large, because it would contain all the images and
the start-up time would be negatively affected by loading invisible images.
A better strategy is to dynamically load the images from your server, as necessary. In this way,
your SWF file stays small, because it does not have to contain invisible images, and your startup time improves.
As part of its implementation, the ActionScript class that defines the <mx:Image> tag is a
subclass of the SWFLoader class. After creating an image, you can use the properties and
methods of the SWFLoader control with your image, including the load() method, which
loads an image file dynamically.
NO T E
The load() method of the SWFLoader control only works with GIF,
JPEG, PNG, and
SWF files; you cannot use it to load SVG files.
The following example uses the load() method to replace the logo.jpg image with the
logowithtext.gif image when the user clicks a button:
<?xml version="1.0"?>
<!-- controls\image\ImageLoad.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
private function afterImage():void {
image1.load('http://localhost:8100/flex/assets/logowithtext.jpg');
}
]]>
</mx:Script>
<mx:VBox id="vbox0"
width="150" height="100">
<mx:Image id="image1" source="logo.jpg"/>
<mx:Button id="myButton"
label="Show Second Image"
click="afterImage();"/>
</mx:VBox>
</mx:Application>
Notice in this example that the application accesses the images in the local file system; they are
not embedded or accessed by URL. Therefore, you have to compile this application with the
use-network flag set to false.
334
Using Controls
The container that holds the image does not adjust the layout of its children when you call the
load() method. Therefore, you typically replace one image with another image of the same
size. If the new image is significantly larger than the original, it can overlay other components
in the container.
You can make the selection of the replacement image based on a user action in your
application. For example, you might want to load an image based on a user selection in a list
box or data grid.
In the next example, you use the index number of the selected item in a data grid to determine
the image to load. In this example, images are named 1.jpg, 2.jpg, 3.jpg, and so on,
corresponding to items in the grid.
// Retrieve the image associated with the item selected in the grid.
private function getImage():void {
var cartGrid = dgrid;
var imageSource:String = 'images/' + cartGrid.getSelectedIndex() +
'.jpg';
image1.load(imageSource);
}
In this example, the images are stored in the images directory. The complete path to an image
is the directory name, the index number, and the file suffix .jpg.
You register this function as the event listener for a change event in the data grid, as follows:
<mx:DataGrid id="dgrid" height="200" width="350" change="getImage();"/>
When a user changes the currently selected item in the data grid, Flex calls the getImage()
function to update the displayed image.
You could modify this example to use information about the selected item to determine the
image to load, rather than using the selected item’s index. For example, the grid could contain
a list of objects, where each object has a property that contains the image name associated
with it.
In addition to the load() method, you can also access other properties of the SWFLoader
control, including percentLoaded. The percentLoaded property is particularly useful
because it lets you to display a progress bar so users know that the application did not become
unresponsive. For a complete list of the SWFLoader properties and methods, see Adobe Flex 2
Language Reference.
VideoDisplay control
Flex supports the VideoDisplay control to incorporate streaming media into Flex applications.
Flex supports the Flash Video File (FLV) file format with this control. This section describes
how to use the VideoDisplay control in your application.
VideoDisplay control
335
Using media in Flex
Media, such as movie and audio clips, are used more and more to provide information to web
users. As a result, you need to provide users with a way to stream the media, and then control
it. The following examples are usage scenarios for media controls:
■
Showing a video message from the CEO of your company
■
Streaming movies or movie previews
■
Streaming songs or song snippets
■
Providing learning material in the form of media
The Flex streaming VideoDisplay control makes it easy to incorporate streaming media into
Flash presentations. Flex supports the Flash Video File (FLV) file format with this control.
You can use this control with video and audio data. When you use the VideoDisplay control
by itself your application provides no mechanism for its users to control the media files.
N OT E
The VideoDisplay control does not support scan forward and scan backward
functionality. Also, the VideoDisplay control does not support accessibility or styles.
About the VideoDisplay control
Flex creates a VideoDisplay control with no visible user interface. It is simply a control to hold
and play media.
N OT E
The user cannot see anything unless some video media is playing.
The playheadTime property of the control holds the current position of the playhead in the
video file, measured in seconds. Most events dispatched by the control include the playhead
position in the associated event object. One use of the playhead position is to dispatch an
event when the video file reaches a specific position. For more information, see “Adding a cue
point” on page 338.
The VideoDisplay control also supports the volume property. This property takes a value
from 0.0 to 1.00; 0.0 is mute and 1.00 is the maximum volume. The default value is 0.75.
Setting the size of a media component
The appearance of any video media playing in a VideoDisplay control is affected by the
following properties:
■
maintainAspectRatio
■
height
336
Using Controls
■
width
When you set maintainAspectRatio to true (the default), the control adjusts the size of the
playing media after the control size has been set. The size of the media is set to maintain its
aspect ratio.
If you omit both width and height properties for the control, Flex makes the control the size
of the playing media. If you specify only one property, and the maintainAspectRatio
property is false, the size of the playing media determines the value of the other property. If
the maintainAspectRatio property is true, the media retains its aspect ratio when resizing.
The following example creates a VideoDisplay control:
<?xml version="1.0"?>
<!-- controls\videodisplay\VideoDisplaySimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:VBox>
<mx:VideoDisplay
source="http://localhost:8100/flex/assets/MyVideo.flv"
height="400"
width="400"/>
</mx:VBox>
</mx:Application>
By default, Flex sizes the VideoDisplay control to the size of the media. If you specify the
width or height property of the control, and either is smaller than the media’s dimensions,
Flex does not change the size of the component. Instead, Flex sizes the media to fit within the
component. If the control’s playback area is smaller than the default size of the media, Flex
shrinks the media to fit inside the control.
Using methods of the VideoDisplay control
You can use the following methods of the VideoDisplay control in your application: close(),
load(), pause(), play(), and stop(). The following example uses the pause() and play()
methods in event listener for two Button controls to pause or play an FLV file:
<?xml version="1.0"?>
<!-- controls\videodisplay\VideoDisplayStopPlay.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:VBox>
<mx:VideoDisplay id="myVid"
source="http://localhost:8100/flex/assets/MyVideo.flv"/>
<mx:Button label="Pause" click="myVid.pause();"/>
<mx:Button label="Play" click="myVid.play();"/>
</mx:VBox>
</mx:Application>
VideoDisplay control
337
Adding a cue point
You can use cue points to trigger events when the playback of your media reaches a specified
location. To use cue points, you set the cuePointManagerClass property to
mx.controls.videoClasses.CuePointManager to enable cue point management, and then pass
an Array of cue points to the cuePoints property of the VideoDisplay control. Each element
of the Array contains two fields. The name field contains an arbitrary name of the cue point.
The time field contains the playhead location, in seconds, of the VideoDisplay control with
which the cue point is associated.
When the playhead of the VideoDisplay control reaches a cue point, it dispatches a cuePoint
event, as the following example shows:
<?xml version="1.0"?>
<!-- controls\videodisplay\VideoDisplayCP.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.events.CuePointEvent;
import mx.controls.videoClasses.CuePointManager;
private function cpHandler(event:CuePointEvent):void {
cp.text="got to cuepoint: " + event.cuePointName + " " +
String(event.cuePointTime);
}
]]>
</mx:Script>
<mx:VBox>
<mx:VideoDisplay
source="http://localhost:8100/flex/assets/MyVideo.flv"
cuePointManagerClass="mx.controls.videoClasses.CuePointManager"
cuePoint="cpHandler(event);">
<mx:cuePoints>
<mx:Object name="first" time="10"/>
<mx:Object name="second" time="20"/>
</mx:cuePoints>
</mx:VideoDisplay>
<mx:TextArea id="cp"/>
</mx:VBox>
</mx:Application>
In this example, the event listener writes a String to the TextArea control when the control
reaches a cue point. The String contains the name and time of the cue point.
338
Using Controls
Adding a cue point by using the CuePointManager class
You can set cue points for the VideoDisplay control by using the cuePointManager property.
This property is of type CuePointManager, where the CuePointManager class defines
methods that you use to programmatically manipulate cue points, as the following example
shows:
<?xml version="1.0"?>
<!-- controls\videodisplay\VideoDisplayCPManager.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.events.CuePointEvent;
[Bindable]
private var myCuePoints:Array = [
{ name: "first", time: 10},
{ name: "second", time: 20} ];
// Set cue points using methods of the CuePointManager class.
private function initCP():void {
myVid.cuePointManager.setCuePoints(myCuePoints);
}
private var currentCP:Object=new Object();
private function cpHandler(event:CuePointEvent):void {
cp.text="go to cuepoint: " + event.cuePointName + " " +
String(event.cuePointTime);
// Remove cue point.
currentCP.name=event.cuePointName;
currentCP.time=event.cuePointTime;
myVid.cuePointManager.removeCuePoint(currentCP);
// Display the number of remaining cue points.
cp.text=cp.text + "\n" + "Cue points remaining: " +
String(myVid.cuePointManager.getCuePoints().length);
}
]]>
</mx:Script>
<mx:VBox>
<mx:VideoDisplay id="myVid"
initialize="initCP();"
cuePointManagerClass="mx.controls.videoClasses.CuePointManager"
source="http://localhost:8100/flex/assets/MyVideo.flv"
cuePoint="cpHandler(event);"/>
<mx:TextArea id="cp" width="200" />
</mx:VBox>
VideoDisplay control
339
</mx:Application>
Streaming video from a camera
You can use the VideoDisplay.attachCamera() method to configure the control to display
a video stream from a camera, as the following example shows:
<?xml version="1.0"?>
<!-- controls\videodisplay\VideoDisplayCamera.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
// Define a variable of type Camera.
import flash.media.Camera;
public var cam:Camera;
public function initCamera():void {
// Initialize the variable.
cam = Camera.getCamera();
myVid.attachCamera(cam)
}
]]>
</mx:Script>
<mx:VideoDisplay id="myVid"
width="320" height="240"
creationComplete="initCamera();"/>
</mx:Application>
In this example, you create a Camera object in the event handler for the creationComplete
event of the VideoDisplay control, then pass the Camera object as the argument to the
attachCamera() method.
340
Using Controls
Using the VideoDisplay control with Flash Media
Server 2
You can use the VideoDisplay control to import a media stream from Macromedia® Flash®
Media Server 2 from Adobe, as the following example shows:
<?xml version="1.0"?>
<!-- controls\videodisplay\VideoDisplayFMS.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox>
<mx:Label text="RTMP FMS 2.0"/>
<mx:VideoDisplay
autoBandWidthDetection="false"
source="rtmp://localhost/videodisplay/bike.flv"/>
</mx:HBox>
</mx:Application>
In this example, you place the bike.flv file in the directory Flash Media Server
2\applications\videodisplay\streams\_definst_.
Notice that you explicitly set the autoBandWidthDetection property to false, its default
value. When the autoBandWidthDetection property is true, you must create the server-side
file main.asc in the directory Flash Media Server 2\applications\videodisplay\scripts, which
implements the following functions:
application.onConnect = function(p_client, p_autoSenseBW) {}
application.calculateClientBw = function(p_client) {}
Client.prototype.getStreamLength = function(p_streamName) {}
The following example shows an implementation of main.asc:
application.onConnect = function(p_client, p_autoSenseBW) {
//Add security code here.
this.acceptConnection(p_client);
if (p_autoSenseBW)
this.calculateClientBw(p_client);
else
p_client.call("onBWDone");
}
Client.prototype.getStreamLength = function(p_streamName) {
return Stream.length(p_streamName);
}
application.calculateClientBw = function(p_client) {
// Add code to set the clients BandWidth.
// Use p_client.getStats() which returns bytes_in
// and bytes_Out and check your bandWidth using
VideoDisplay control
341
// p_client.call("onBWCheck", result, p_client.payload).
p_client.call("onBWDone");
}
For more information on main.asc, see the Flash Media Server 2 documentation.
Specifying the AMF version for Flash Media Server
When you read from or write to a NetConnection, NetStream, or SharedObject object as
binary data, the objectEncoding property of the object indicates which Action Message
Format (AMF) version to use: the ActionScript 3.0 format or the ActionScript 1.0 or
ActionScript 2.0 format. The possible value of the objectEncoding property include the
following:
AMF0
Objects are serialized using the AMF format for ActionScript 1.0 and 2.0.
AMF3
Objects are serialized using the AMF format for ActionScript 3.0.
DEFAULT
Objects are serialized using the default format for your version of Flash Player.
All versions of Flash Media Server use the AMF0 encoding. Therefore, Flex applications must
set the objectEncoding property of all NetConnection and SharedObject objects used with
Flash Media Server to AMF0. For NetStream, the objectEncoding property is read only. Any
FAP connections or RTMP connections to your own server can use AMF3.
ColorPicker control
The ColorPicker control lets users select a color from a drop-down swatch panel (palette). It
initially appears as a preview sample with the selected color. When a user selects the control, a
color swatch panel appears. The panel includes a sample of the selected color and a color
swatch panel. By default, the swatch panel displays the web-safe colors (216 colors, where
each of the three primary colors has a value that is a multiple of 33, such as #CC0066)
For complete reference information, see ColorPicker in Adobe Flex 2 Language Reference.
About the ColorPicker control
When you open the ColorPicker control, the swatch panel expands over other controls on the
application, and normally opens downwards. If the swatch panel would hit the lower
boundary of the application, but could fit above color picker button, it opens upward.
If you set the showTextField property to true (the default), the panel includes a text box
with a label for the selected color. If you display a text box and set the editable property to
true (the default), the user can specify a color by entering a hexadecimal value.
342
Using Controls
The following example shows a collapsed and expanded ColorPicker control that uses the
default settings of the mx:ColorPicker tag:
Collapsed
Expanded
Flex populates the color swatch panel and the text box from a data provider. By default, the
control uses a data provider that includes all the web-safe colors. If you use your own data
provider you can specify the following:
The colors to display
You must specify the colors if you use your own dataProvider.
Labels to display in the text box for the colors
If you do not specify text labels, Flex uses
the hexadecimal color values.
Additional information for each color This information can include any information that is
of use to your application, such as IDs or descriptive comments.
The following image shows an expanded ColorPicker control that uses a custom data provider
that includes color label values. It also uses styles to set the sizes of the display elements.
ColorPicker control
343
The ColorPicker control has the following default sizing characteristics:
Property
Default value
Default size
ColorPicker: 22 by 22 pixels
Swatch panel: Sized to fit the ColorPicker control width
Minimum size
0 by 0
Maximum size
Undefined
Creating a ColorPicker control
You use the <mx:ColorPicker> tag to define a ColorPicker 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. For example, the ColorPicker control in the image was generated
using the following, minimal, code:
<mx:ColorPicker id="cp"/>
The ColorPicker control uses a list-based data provider for the colors. For more information
on this type of data provider, see Chapter 7, “Using Data Providers and Collections,” on
page 161. If you omit the data provider, the control uses a default data provider with the websafe colors. The data provider can be an array of colors or an array of objects. The following
example populates a ColorPicker with a simple array of colors. For information on using a
more complex dataProvider, see “Using Objects to populate a ColorPicker control”
on page 346.
<?xml version="1.0"?>
<!-- controls\colorpicker\CPSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
[Bindable]
public var simpleDP:Array = ['0x000000', '0xFF0000', '0xFF8800',
'0xFFFF00', '0x88FF00', '0x00FF00', '0x00FF88', '0x00FFFF',
'0x0088FF', '0x0000FF', '0x8800FF', '0xFF00FF', '0xFFFFFF'];
]]>
</mx:Script>
<mx:ColorPicker id="cp" dataProvider="{simpleDP}"/>
</mx:Application>
N O TE
344
You can also specify the data for the ColorPicker control using a <mx:dataProvider> child
tag; for an example, see “Using custom field names” on page 348.
Some examples in this section use simple Arrays as custom data sources, not
ArrayCollections, because the array contents are static.
Using Controls
You typically use events to handle user interaction with a ColorPicker control. The following
example adds an event listener for a change event and an open event to the previous example
ColorPicker control:
<?xml version="1.0"?>
<!-- controls\colorpicker\CPEvents.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
//Import the event classes.
import mx.events.DropdownEvent;
import mx.events.ColorPickerEvent;
[Bindable]
public var simpleDP:Array = ['0x000000', '0xFF0000', '0xFF8800',
'0xFFFF00', '0x88FF00', '0x00FF00', '0x00FF88', '0x00FFFF',
'0x0088FF', '0x0000FF', '0x8800FF', '0xFF00FF', '0xFFFFFF'];
public function openEvt(event:DropdownEvent):void {
forChange.text="Opened";
}
public function changeEvt(event:ColorPickerEvent):void {
forChange.text="Selected Item: "
+ event.currentTarget.selectedItem + " Selected Index: "
+ event.currentTarget.selectedIndex;
}
]]>
</mx:Script>
<mx:VBox>
<mx:TextArea id="forChange"
width="150"/>
<mx:ColorPicker id="cp"
dataProvider="{simpleDP}"
open="openEvt(event);"
change="changeEvt(event);"/>
</mx:VBox>
</mx:Application>
The ColorPicker control dispatches open event when the swatch panel opens and Dispatches
a change event when the value of the control changes due to user interaction. The
currentTarget property of the object passed to the event listener contains a reference to the
ColorPicker control. In this example, the event listeners use two properties of the ColorPicker
control, selectedItem and selectedIndex. Every change event updates the TextArea
control with the selected item and the item’s index in the control, and an open event displays
the word Opened.
ColorPicker control
345
If you populate the ColorPicker control from an array of color values, the
target.selectedItem field contains the hexadecimal color value. If you populate it from an
array of Objects, the target.selectedItem field contains a reference to the object that
corresponds to the selected item.
The index of items in the ColorPicker control is zero-based, which means that values are 0, 1,
2, ... , n - 1, where n is the total number of items; therefore, the target.selectedIndex
value is zero-based, and a value of 2 in the preceding example refers to the data provider entry
with color 0xFF8800.
Using Objects to populate a ColorPicker control
You can populate a ColorPicker control with an Array of Objects. By default, the ColorPicker
uses two fields in the Objects: one named color, and another named label. The label field
value determines the text in the swatch panel’s text field. If the Objects do not have a label
field, the control uses the color field value in the text field. You can use the ColorPicker
control’s colorField and labelField properties to specify different names for the color and
label fields. The Objects can have additional fields, such as a color description or an internal
color ID, that you can use in your ActionScript.
Example: ColorPicker control that uses Objects
The following example shows a ColorPicker that uses an Array of Objects with three fields:
color, label, and descript.
<?xml version="1.0"?>
<!-- controls\colorpicker\CPObjects.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.events.ColorPickerEvent;
import mx.events.DropdownEvent;
[Bindable]
public var complexDPArray:Array = [
{label:"Yellow", color:"0xFFFF00",
descript:"A bright, light color."},
{label:"Hot Pink", color:"0xFF66CC",
descript:"It's HOT!"},
{label:"Brick Red", color:"0x990000",
descript:"Goes well with warm colors."},
{label:"Navy Blue", color:"0x000066",
descript:"The conservative favorite."},
{label:"Forest Green", color:"0x006600",
descript:"Great outdoorsy look."},
346
Using Controls
{label:"Grey", color:"0x666666",
descript:"An old reliable."}]
public function openEvt(event:DropdownEvent):void {
descriptBox.text="";
}
public function changeEvt(event:ColorPickerEvent):void {
descriptBox.text=event.currentTarget.selectedItem.label
+ ": " + event.currentTarget.selectedItem.descript;
}
]]>
</mx:Script>
<!-- Convert the Array to an ArrayCollection. Do this if
you might change the colors in the panel dynamically. -->
<mx:ArrayCollection id="complexDP" source="{complexDPArray}"/>
<mx:VBox>
<mx:TextArea id="descriptBox"
width="150" height="50"/>
<mx:ColorPicker id="cp"
height="50" width="150"
dataProvider="{complexDP}"
change="changeEvt(event);"
open="openEvt(event);"
swatchWidth="25"
swatchHeight="25"
textFieldWidth="95"
editable="false"/>
</mx:VBox>
</mx:Application>
In this example, the selectedItem property contains a reference to the object defining the
selected item. The example uses selectedItem.label to access the object’s label property
(the color name), and selectedItem.descript to access the object’s descript property (the
color description). Every change event updates the TextArea control with the label
property of the selected item and the item’s description. The open event clears the current text
in the TextArea control each time the user opens up the ColorPicker to display the swatch
panel.
This example also uses several of the ColorPicker properties and styles to specify the control’s
behavior and appearance. The editable property prevents users from entering a value in the
color label box (so they can only select the colors from the dataProvider). The swatchWidth
and swatchHeight styles control the size of the color samples in the swatch panel, and the
textFieldWidth style ensures that the text field is long enough to accommodate the longest
color name.
ColorPicker control
347
Using custom field names
In some cases, you might want to use custom names for the color and label fields; for example,
if the data comes from an external data source with custom column names. The following
code changes the previous example to use custom color and label fields called cName and
cVal. It also shows how to use an <mx:dataProvider> tag to populate the data provider.
<?xml version="1.0"?>
<!-- controls\colorpicker\CPCustomFieldNames.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.events.ColorPickerEvent;
import mx.events.DropdownEvent;
public function openEvt(event:DropdownEvent):void {
descriptBox.text="";
}
public function changeEvt(event:ColorPickerEvent):void {
descriptBox.text=event.currentTarget.selectedItem.cName
+ ": " + event.currentTarget.selectedItem.cDescript;
}
]]>
</mx:Script>
<mx:VBox>
<mx:TextArea id="descriptBox"
width="150" height="50"/>
<mx:ColorPicker id="cp"
height="50" width="150"
labelField="cName"
colorField="cVal"
change="changeEvt(event)"
open="openEvt(event)"
swatchWidth="25"
swatchHeight="25"
textFieldWidth="95"
editable="false">
<mx:dataProvider>
<mx:ArrayCollection>
<mx:source>
<mx:Object cName="Yellow" cVal="0xFFFF00"
cDescript="A bright, light color."/>
<mx:Object cName="Hot Pink" cVal="0xFF66CC"
cDescript="It's HOT!"/>
<mx:Object cName="Brick Red" cVal="0x990000"
cDescript="Goes well with warm colors."/>
<mx:Object cName="Navy Blue" cVal="0x000066"
348
Using Controls
cDescript="The conservative favorite."/>
<mx:Object cName="Forest Green" cVal="0x006600"
cDescript="Great outdoorsy look."/>
<mx:Object cName="Grey" cVal="0x666666"
cDescript="An old reliable."/>
</mx:source>
</mx:ArrayCollection>
</mx:dataProvider>
</mx:ColorPicker>
</mx:VBox>
</mx:Application>
User interaction
A ColorPicker control can be editable or noneditable. In a noneditable ColorPicker control,
the user must select a color from among the swatch panel options. In an editable ColorPicker
control, a user can select swatch panel items or enter a hexadecimal color value directly into
the label text field at the top of the swatch panel. Users can type numbers and uppercase or
lowercase letters in the ranges a-f and A-F in the text box; it ignores all other non-numeric
characters.
Mouse interaction
You can use the mouse to navigate and select from the control:
■
Click the collapsed control to display or hide the swatch panel.
■
Click any swatch in the swatch panel to select it and close the panel.
■
Click outside the panel area to close the panel without making a selection.
■
Click in the text field to move the text entry cursor.
Keyboard interaction
If the ColorPicker is editable, and the swatch panel has the focus, alphabetic keys in the range
A-F and a-f, numeric keys, and the Backspace and Delete keys enter and remove text in the
color text box. You can also use the following keystrokes to control the ColorPicker:
Key
Description
Control+Down Arrow Opens the swatch panel and puts the focus on the selected swatch.
Control+Up Arrow
Closes the swatch panel, if open.
Home
Moves the selection to the first color in a row of the swatch panel. Has
no effect if there is a single column.
ColorPicker control
349
Key
Description
End
Moves the selection to the last color in a row of the swatch panel. Has
no effect if there is a single column.
Page Up
Moves the selection to the top color in a column of the swatch panel.
Has no effect if there is a single row.
Page Down
Moves the selection to the bottom color in a column of the swatch
panel. Has no effect if there is a single row.
Escape
Closes the swatch panel without changing the color in the color
picker.
Most Web browsers do not support using his key.
Enter
Selects the current color from the swatch panel and closes the
swatch panel; equivalent to clicking a color swatch. If the focus is on
the text field of an editable ColorPicker, selects the color specified by
the field text.
Arrows
When the swatch panel is open, moves the focus to the next color left,
right, up, and down in the swatch grid. On a single-row swatch panel,
Up and Right Arrow keys are equivalent, and Down and Left Arrow
keys are equivalent.
On a multirow swatch panel, the selection wraps to the beginning or
end of the next or previous line. On a single-row swatch panel,
pressing the key past the beginning or end of the row loops around on
the row.
When the swatch panel is closed, but has the focus, the Up and Down
Arrow keys have no effect. The Left and Right Arrow keys change the
color picker selection, moving through the colors as if the panel were
open.
NO T E
350
When the swatch panel is open, you cannot use the Tab and Shift+Tab keys to move the
focus to another object.
Using Controls
Alert control
All Flex components can call the static show() method of the Alert class to open a pop-up
modal dialog box with a message and an optional title, buttons, and icons. The following
example shows an Alert control pop-up dialog box:
The Alert control closes when you select a button in the control, or press the Escape key.
The Alert.show() method has the following syntax:
public static show(
text:String,
title:String = null,
flags:uint = mx.controls.Alert.OK,
parent:Sprite = null,
clickListener:Function = null,
iconClass:Class = null,
defaultButton:uint = mx.controls.Alert.OK) : Alert
This method returns an Alert control object.
The following table describes the arguments of the show() method:
Argument
Description
text
(Required) Specifies the text message displayed in the dialog box.
title
Specifies the dialog box title. If omitted, displays a blank title bar.
flags
Specifies the button(s) to display in the dialog box. The options are as follows:
mx.controls.Alert.OK OK button
mx.controls.Alert.YES Yes button
mx.controls.Alert.NO No button
mx.controls.Alert.CANCEL Cancel button
Each option is a bit value and can be combined with other options using the
pipe '|' operator. The buttons will appear in the order listed here regardless of
the order you specify them in your code.The default value is
mx.controls.Alert.OK.
parent
The parent object of the Alert control.
Alert control
351
Argument
Description
clickListener Specifies the listener for click events from the buttons.
The event object passed to this handler is an instance of the CloseEvent
class. The event object contains the detail field, which is set to the button
flag that was clicked (mx.controls.Alert.OK, mx.controls.Alert.CANCEL,
mx.controls.Alert.YES, or mx.controls.Alert.NO).
iconClass
Specifies an icon to display to the left of the message text in the dialog box.
defaultButton Specifies the default button using one of the valid values for the flags
argument. This is the button that is selected when the user presses the Enter
key. The default value is Alert.OK.
Pressing the Escape key triggers the Cancel or No button just as if you clicked
it.
To use the Alert control, you first import the Alert class into your application. then call the
show() method, as the following example shows:
<?xml version="1.0"?>
<!-- controls\alert\AlertSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
]]>
</mx:Script>
<mx:TextInput id="myInput"
width="150"
text=""/>
<mx:Button id="myButton"
label="Copy Text"
click="myText.text = myInput.text;
Alert.show('Text Copied!', 'Alert Box', mx.controls.Alert.OK);"/>
<mx:TextInput id="myText"/>
</mx:Application>
In this example, selecting the Button control copies text from the TextInput control to the
TextArea control, and displays the Alert control.
352
Using Controls
You can also define an event listener for the Button control, as the following example shows:
<?xml version="1.0"?>
<!-- controls\alert\AlertSimpleEvent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
private function alertListener():void {
myText.text = myInput.text;
Alert.show("Text Copied!", "Alert Box", Alert.OK);
}
]]>
</mx:Script>
<mx:TextInput id="myInput"
width="150"
text=""/>
<mx:Button id="myButton"
label="Copy Text"
click="alertListener();"/>
<mx:TextInput id="myText"/>
</mx:Application>
NO TE
After the show() method creates the dialog box, Flex continues processing of your
application; it does not wait for the user to close the dialog box.
Alert control
353
Sizing the Alert control
The Alert control automatically sizes itself to fit its text, buttons, and icon. You can explicitly
size an Alert control using the Alert object returned from the show() method, as the following
example shows:
<?xml version="1.0"?>
<!-- controls\alert\AlertSize.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
// Define variable to hold the Alert object.
public var myAlert:Alert;
private function openAlert():void {
myAlert = Alert.show("Copy Text?", "Alert",
Alert.OK
| Alert.CANCEL);
// Set the height and width of the Alert control.
myAlert.height=150;
myAlert.width=150;
}
]]>
</mx:Script>
<mx:TextInput id="myInput"
width="150"
text=""/>
<mx:Button id="myButton"
label="Copy Text"
click="openAlert();"/>
<mx:TextInput id="myText"/>
</mx:Application>
In this example, you set the height and width properties of the Alert object to explicitly size
the control.
Using event listeners with the Alert control
The next example adds an event listener to the Alert control pop-up dialog box. An event
listener lets you perform processing when the user selects a button of the Alert control. The
event object passed to the event listener is of type CloseEvent.
354
Using Controls
In the next example, you only copy the text when the user selects the OK button in the Alert
control:
<?xml version="1.0"?>
<!-- controls\alert\AlertEvent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.CloseEvent;
private function alertListener(eventObj:CloseEvent):void {
// Check to see if the OK button was pressed.
if (eventObj.detail==Alert.OK) {
myText.text = myInput.text;
}
}
]]>
</mx:Script>
<mx:TextInput id="myInput"
width="150"
text="" />
<mx:Button id="myButton"
label="Copy Text"
click='Alert.show("Copy Text?", "Alert",
Alert.OK | Alert.CANCEL, this,
alertListener, null, Alert.OK);'/>
<mx:TextInput id="myText"/>
</mx:Application>
In this example, you define an event listener for the Alert control. Within the body of the
event listener, you determine which button was pressed by examining the detail property of
the event object. The event object is an instance of the CloseEvent class. If the user pressed the
OK button, copy the text. If the user pressed any other button, or pressed the Escape key, do
not copy the text.
Alert control
355
Specifying an Alert control icon
You can include an icon in the Alert control that appears to the left of the Alert control text.
This example modifies the example from the previous section to add the Embed metadata tag
to import the icon. For more information on importing resources, see Chapter 4, “Using
ActionScript,” on page 55.
<?xml version="1.0"?>
<!-- controls\alert\AlertIcon.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.CloseEvent;
[Embed(source="assets/alertIcon.jpg")]
[Bindable]
public var iconSymbol:Class;
private function alertListener(eventObj:CloseEvent):void {
// Check to see if the OK button was pressed.
if (eventObj.detail==Alert.OK) {
myText.text = myInput.text;
}
}
]]>
</mx:Script>
<mx:TextInput id="myInput"
width="150"
text=""/>
<mx:Button id="myButton"
label="Copy Text"
click='Alert.show("Copy Text?", "Alert",
Alert.OK | Alert.CANCEL, this,
alertListener, iconSymbol, Alert.OK );'/>
<mx:TextInput id="myText"/>
</mx:Application>
ProgressBar control
The ProgressBar control provides a visual representation of the progress of a task over time.
There are two types of ProgressBar controls: determinate and indeterminate. A determinate
ProgressBar control is a linear representation of the progress of a task over time. You can use
this when the user is required to wait for an extended period of time, and the scope of the task
is known.
356
Using Controls
An indeterminate ProgressBar control represents time-based processes for which the scope is
not yet known. As soon as you can determine the scope, you should use a determinate
ProgressBar control.
The following example shows both types of ProgressBar controls:
Determinate ProgressBar control
Indeterminate ProgressBar control
Use the ProgressBar control when the user is required to wait for completion of a process over
an extended period of time. You can attach the ProgressBar control to any kind of loading
content. A label can display the extent of loaded contents when enabled.
The ProgressBar control has the following default properties:
Property
Default value
default size
150 pixels wide and 4 pixels high
Minimum size
0
Maximum size
Undefined
ProgressBar control modes
You use the mode property to specify the operating mode of the ProgressBar control. The
ProgressBar control supports the following modes of operation:
event
Use the source property to specify a loading process that emits progress and
events. For example, the SWFLoader and Image controls emit these events as part
of loading a file. You typically use a determinate ProgressBar in this mode. This is the default
mode.
complete
You also use this mode if you want to measure progress on multiple loads; for example, if you
reload an image, or use the SWFLoader and Image controls to load multiple images.
polled
Use the source property to specify a loading process that exposes the
and getsBytesTotal() methods. For example, the SWFLoader and
Image controls expose these methods. You typically use a determinate ProgressBar in this
mode.
getBytesLoaded()
manual
Set the maximum, minimum, and indeterminate properties along with calls to the
method. You typically use an indeterminate ProgressBar in this mode.
setProgress()
ProgressBar control
357
Creating a ProgressBar control
You use the <mx:ProgressBar> tag to define a ProgressBar 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.
The following example uses the default event mode to track the progress of loading an image
using the Image control:
<?xml version="1.0"?>
<!-- controls\pbar\PBarSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
public function initImage():void {
image1.load('http://localhost:8100/flex/assets/DSC00034.JPG');
}
]]>
</mx:Script>
<mx:VBox id="vbox0"
width="600" height="600">
<mx:Canvas>
<mx:ProgressBar width="200" source="image1"/>
</mx:Canvas>
<mx:Button id="myButton"
label="Show"
click="initImage();"/>
<mx:Image id="image1"
height="600" width="600"
autoLoad="false"
visible="true"/>
</mx:VBox>
</mx:Application>
In this mode, the Image control issues progress events during the load, and a complete
event when the load completes.
The <mx:Image> tag exposes the getBytesLoaded() and getBytesTotal() methods, so you
could also use polled mode, as the following example shows:
<mx:ProgressBar width="200" source="image1" mode="polled"/>
In manual mode, mode="manual", you use an indeterminate ProgressBar control with the
maximum and minimum properties and the setProgress() method. The setProgress()
method has the following method signature:
setProgress(Number completed, Number total)
358
Using Controls
Specifies the progress made in the task, and must be between the maximum and
For example, if you were tracking the number of bytes to load, this would be
the number of bytes already loaded.
completed
minimum values.
Specifies the total task. For example, if you were tracking bytes loaded, this would be
the total number of bytes to load. Typically, this is the same value as maximum.
total
To measure progress, you make explicit calls to the setProgress() method to update the
ProgressBar control.
Defining the label of a ProgressBar control
By default, the ProgressBar displays the label LOADING xx%, where xx is the percent of the
image loaded. You use the label property to specify a different text string to display.
The label property lets you include the following special characters in the label text string:
%1
Corresponds to the current number of bytes loaded.
%2
Corresponds to the total number of bytes.
%3
Corresponds to the percent loaded.
%%
Corresponds to the % sign.
For example, to define a label that displays as
Loading Image 1500 out of 78000 bytes, 2%
ProgressBar control
359
use the following code:
<?xml version="1.0"?>
<!-- controls\pbar\PBarLabel.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
public function initImage():void {
image1.load('http://localhost:8100/flex/assets/DSC00034.JPG');
}
]]>
</mx:Script>
<mx:VBox id="vbox0"
width="600" height="600">
<mx:Canvas>
<mx:ProgressBar
width="300"
source="image1"
mode="polled"
label="Loading Image %1 out of %2 bytes, %3%%"
labelWidth="400"/>
</mx:Canvas>
<mx:Button id="myButton"
label="Show"
click="initImage();"/>
<mx:Image id="image1"
height="600" width="600"
autoLoad="false"
visible="true"/>
</mx:VBox>
</mx:Application>
360
Using Controls
HRule and VRule controls
The HRule (Horizontal Rule) control creates a single horizontal line and the VRule (Vertical
Rule) control creates a single vertical line. You typically use these controls to create dividing
lines within a container.
The following image shows an HRule and a VRule control:
HRule control
VRule control
The HRule and VRule controls have the following default properties:
Property
Default value
Default size
Horizontal Rule The default width is 100 pixels, and the default height is 2
pixels. By default, the HRule control is not resizable; set width and height to
percentage values to enable resizing.
Vertical Rule The default height is 100 pixels, and the default width is 2
pixels. By default, the VRule control is not resizable; set width and height to
percentage values to enable resizing.
strokeWidth
2 pixels
strokeColor
0xC4CCCC
shadowColor
0xEEEEEE
HRule and VRule controls
361
Creating HRule and VRule controls
You define HRule and VRule controls in MXML using the <mx:HRule> and <mx:VRule>
tags, 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 an ActionScript block.
<?xml version="1.0"?>
<!-- controls\rule\RuleSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:VBox>
<mx:Label text="Above"/>
<mx:HRule/>
<mx:Label text="Below"/>
</mx:VBox>
<mx:HBox>
<mx:Label text="Left"/>
<mx:VRule/>
<mx:Label text="Right"/>
</mx:HBox>
</mx:Application>
This example creates the output shown in the preceding image.
You can also use properties of the HRule and VRule controls to specify line width, stroke
color, and shadow color, as the following example shows:
<?xml version="1.0"?>
<!-- controls\rule\RuleProps.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:VBox>
<mx:Label
<mx:HRule
<mx:Label
</mx:VBox>
<mx:HBox>
<mx:Label
<mx:VRule
<mx:Label
</mx:HBox>
</mx:Application>
362
Using Controls
text="Above"/>
shadowColor="0xEEEEEE"/>
text="Below"/>
text="Left"/>
strokeWidth="10" strokeColor="0xC4CCCC"/>
text="Right"/>
This code produces the following image:
Sizing HRule and VRule controls
For the HRule and VRule controls, the strokeWidth property determines how Flex draws
the line, as follows:
■
If you set the strokeWidth property to 1, Flex draws a 1-pixel-wide line.
■
If you set the strokeWidth property to 2, Flex draws the rule as two adjacent 1-pixel-wide
lines, horizontal for an HRule control or vertical for a VRule control. This is the default
value.
■
If you set the strokeWidth property to a value greater than 2, Flex draws the rule as a
hollow rectangle with 1-pixel-wide edges.
The following example shows all three options:
VRule control
VRule control
VRule control
strokeWidth = 1
default strokeWidth = 2
strokeWidth = 10
If you set the height property of an HRule control to a value greater than the strokeWidth
property, Flex draws the rule within a rectangle of the specified height, and centers the rule
vertically within the rectangle. The height of the rule is the height specified by the
strokeWidth property.
HRule and VRule controls
363
If you set the width property of a VRule control to a value greater than the strokeWidth
property, Flex draws the rule within a rectangle of the specified width, and centers the rule
horizontally within the rectangle. The width of the rule is the width specified by the
strokeWidth property.
If you set the height property of an HRule control or the width property of a VRule control
to a value smaller than the strokeWidth property, the rule is drawn as if it had a
strokeWidth property equal to the height or width property.
N OT E
If the height and width properties are specified as percentage values, the actual pixel
values are calculated before the height and width properties are compared to the
strokeWidth property.
The strokeColor and shadowColor properties determine the colors of the HRule and VRule
controls. The strokeColor property specifies the color of the line as follows:
■
If you set the strokeWidth property to 1, specifies the color of the entire line.
■
If you set the strokeWidth property to 2, specifies the color of the top line for an HRule
control, or the left line for a VRule control.
■
If you set the strokeWidth property to a value greater than 2, specifies the color of the
top and left edges of the rectangle.
The shadowColor property specifies the shadow color of the line as follows:
■
If you set the strokeWidth property to 1, does nothing.
■
If you set the strokeWidth property to 2, specifies the color of the bottom line for an
HRule control, or the right line for a VRule control.
■
If you set the strokeWidth property to a value greater than 2, specifies the color of the
bottom and right edges of the rectangle.
Setting style properties
The strokeWidth, strokeColor, and shadowColor properties are style properties.
Therefore, you can set them in MXML as part of the tag definition, set them using the
<mx:Style> tag in MXML, or set them using the setStyle() method in ActionScript.
364
Using Controls
The following example uses the <mx:Style> tag to set the default value of the strokeColor
property of all HRule controls to #00FF00 (lime green), and the default value of the
shadowColor property to #0000FF (blue). This example also defines a class selector, called
thickRule, with a strokeWidth of 5 that you can use with any instance of an HRule control
or VRule control:
<?xml version="1.0"?>
<!-- controls\rule\RuleStyles.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Style>
.thickRule {strokeWidth:5}
HRule {strokeColor:#00FF00; shadowColor:#0000FF}
</mx:Style>
<mx:HRule styleName="thickRule"/>
</mx:Application>
This example produces the following image:
ScrollBar control
The VScrollBar (vertical ScrollBar) control and HScrollBar (horizontal ScrollBar) controls let
the user control the portion of data that is displayed when there is too much data to fit in the
display area.
Although you can use the VScrollBar control and HScrollBar control as stand-alone controls,
they are usually combined with other components as part of a custom component to provide
scrolling functionality. For more information, see Creating and Extending Flex 2 Components.
ScrollBar controls consists of four parts: two arrow buttons, a track, and a thumb. The
position of the thumb and display of the buttons depends on the current state of the ScrollBar
control. The ScrollBar control uses four parameters to calculate its display state:
■
Minimum range value
■
Maximum range value
■
Current position; must be within the minimum and maximum range values
■
Viewport size; represents the number of items in the range that can be displayed at once
and must be equal to or less than the range
ScrollBar control
365
Creating a ScrollBar control
You define a ScrollBar control in MXML using the <mx:VScrollbar> tag for a vertical
ScrollBar or the <mx:HScrollBar> tag for a horizontal ScrollBar, 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\bar\SBarSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.events.ScrollEvent;
// Event handler function to display the scroll location.
private function myScroll(event:ScrollEvent):void {
showPosition.text = "VScrollBar properties summary:" + '\n' +
"------------------------------------" + '\n' +
"Current scroll position: " +
event.currentTarget.scrollPosition + '\n' +
"The maximum scroll position: " +
event.currentTarget.maxScrollPosition + '\n' +
"The minimum scroll position: " +
event.currentTarget.minScrollPosition;
}
]]>
</mx:Script>
<mx:Label
width="100%"
color="blue"
text="Click on the scroll bar to view its properties."/>
<mx:VScrollBar id="bar"
height="100%"
minScrollPosition="0"
maxScrollPosition="{this.width - 20}"
lineScrollSize="50"
pageScrollSize="100"
repeatDelay="1000"
repeatInterval="500"
scroll="myScroll(event);"/>
<mx:TextArea id="showPosition"
height="100%" width="100%"
color="blue"/>
</mx:Application>
366
Using Controls
Sizing a ScrollBar control
The ScrollBar control does not display correctly if it is sized smaller than the height of the up
arrow and down arrow buttons. There is no error checking for this condition. Adobe
recommends that you hide the ScrollBar control in such a condition. If there is not enough
room for the thumb, the thumb is made invisible.
User interaction
Use the mouse to click the various portions of the ScrollBar control, which dispatches events
to listeners. The object listening to the ScrollBar control is responsible for updating the
portion of data displayed. The ScrollBar control updates itself to represent the new state after
the action has taken place.
ScrollBar control
367
368
Using Controls
10
CHAPTER 10
Using Text Controls
Text controls can display text, let the user enter text, or do both. This topic describes how to
use text controls in an Adobe Flex application.
Contents
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
About text controls
You use Flex text-based controls to display text and to let users enter text into your
application. The following table lists the controls, and indicates whether the control can have
multiple lines of input instead of a single line of text, and whether the control can accept user
input:
Control
Multiline
Allows user Input
Label
No
No
TextInput
No
Yes
Text
Yes
No
TextArea
Yes
Yes
RichTextEditor
Yes
Yes
369
All controls except the RichTextEditor control are single components with a simple text
region; for example, the following image shows a TextInput control in a simple form:
The following code produces the preceding image:
<?xml version="1.0"?>
<!-- textcontrols/FormItemLabel.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
<mx:Form id="myForm" width="500" backgroundColor="#909090">
<!-- Use a FormItem to label the field. -->
<mx:FormItem label="First Name">
<mx:TextInput id="ti1" width="150"/>
</mx:FormItem>
</mx:Form>
</mx:Application>
The RichTextEditor control is a compound control; it consists of a Panel control that contains
a TextArea control and a ControlBar with several controls for specifying the text format and
HTTP links. The following image shows a RichTextEditor control:
370
Using Text Controls
The following code produces the preceding image:
<?xml version="1.0"?>
<!-- textcontrols/RTECDATA.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
<mx:RichTextEditor id="rte1" title="Rich Text Editor">
<mx:htmlText>
<![CDATA[
<p align='center'><b><font size='16'>HTML Text</font></b>
</p>This paragraph has <font color='#006666'><b>bold teal text.
</b></font>
]]>
</mx:htmlText>
</mx:RichTextEditor>
</mx:Application>
Flex text-based controls let you set and get text by using the following properties:
text Plain text without formatting information. For information on using the text property,
see “Using the text property” on page 371.
htmlText
Rich text that represents formatting by using a subset of HTML tags, and can
include bulleted text and URL links. For information on using the htmlText property, see
“Using the htmlText property” on page 376.
Both properties set the same underlying text, but you can use different formats. For example,
you can do the following to set, modify, and get text:
■
You can set formatted text by using the htmlText property, and get it back as a plain text
string by using the text property.
■
You can set formatted text in user-editable text controls (TextInput, TextArea,
RichTextEditor) by setting the text string with the text property and formatting a section
of this text by using the TextRange class. If you get the text back by using the htmlText
property, the property string includes HTML tags for the formatting. For more
information on using the TextRange class, see “Selecting and modifying text”
on page 387.
Using the text property
You can use the text property to specify the text string that appears in a text control or to get
the text in the control as a plain text String. When you set this property, any HTML tags in
the text string appear in the control as literal text.
Using the text property
371
You cannot specify text formatting when you set the text property, but you can format the
text in the control. You can use the text control styles to format all of the text in the control,
and you can use the TextRange class to format ranges of text. (For more information on using
the TextRange class, see “Selecting and modifying text” on page 387.)
The following code line uses a text property to specify label text:
<mx:Label text="This is a simple text label"/>
The way you specify special characters, including quotation marks, greater than and less than
signs, and apostrophes, depends on whether you use them in MXML tags or in ActionScript.
It also depends on whether you specify the text directly or wrap the text in a CDATA section.
NO T E
If you specify the value of the text property by using a string directly in MXML, Flex
collapses white space characters. If you specify the value of the text property in
ActionScript, Flex does not collapse white space characters.
Specifying special characters in the text property
The following rules specifying how to include special characters in the text property of a text
control MXML tag, either in a property assignment, such as text="the text", or in the
body of an <mx:text> subtag.
In standard text
The following rules determine how you use special characters if you do not
use a CDATA section.
■
To use the special characters left angle bracket (<), right angle bracket (>), and ampersand
(&), insert the XML character entity equivalents of &lt;, &gt;, and &amp;, respectively.
You can also use &quot; and &apos; for double-quotation marks (") and single-quotation
marks ('), and you can use numeric character references, such as &#165 for the Yen mark
(¥). Do not use any other named character entities; Flex treats them as literal text.
■
You cannot use the character that encloses the property text string inside the string. If you
surround the string in double-quotation marks ("), use the escape sequence \" for any
double-quotation marks in the string. If you surround the string in single-quotation
marks (') use the escape sequence \' for any single-quotation marks in the string. You can
use single-quotation marks inside a string that is surrounded in double-quotation marks,
and double-quotation marks inside a string that is surrounded in single-quotation marks.
■
Flex text controls ignore escape characters such as \t or \n in the text property. They
ignore or converts to spaces, tabs and line breaks, depending on whether you are
specifying a property assignment or an <mx:text> subtag. To include line breaks, put the
text in a CDATA section. In the Text control text="string" attribute specifications, you
can also specify them as numeric character entities, such as &#013; for a Return character
or &#009; for a Tab character, but you cannot do this in an <mx:text> subtag.
372
Using Text Controls
The following code example uses the text property with standard text:
<?xml version="1.0"?>
<!-- textcontrols/StandardText.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" height="400">
<mx:Text width="400" text="This string contains a less than, &lt;,
greater than, &gt;, ampersand, &amp;, apostrophe, ', and
quotation mark &quot;."/>
<mx:Text width="400" text='This string contains a less than, &lt;,
greater than, &gt;, ampersand, &amp;, apostrophe, &apos;, and
quotation mark, ".'/>
<mx:Text width="400">
<mx:text>
This string contains a less than, &lt;, greater than,
&gt;, ampersand, &amp;, apostrophe, ', and quotation mark, ".
</mx:text>
</mx:Text>
</mx:Application>
The resulting application contains three almost identical text controls, each with the
following text. The first two controls, however, convert any tabs in the text to spaces.
This string contains a less than, <, greater than, >, ampersand, &,
apostrophe, ', and quotation mark, ".
In a CDATA section
If you wrap the text string in the CDATA tag, the following rules apply:
■
You cannot use a CDATA section in a property assignment statement in the text control
opening tag; you must define the property in an <mx:text> child tag.
■
Text inside the CDATA section appears as it is entered, including white space characters.
Use literal characters, such as " or < for special characters, and use standard return and tab
characters. Character entities, such as &gt;, and backslash-style escape characters, such as
\n, appear as literal text.
Using the text property
373
The following code example follows these CDATA section rules. The second and third lines
of text in the <mx:text> tag are not indented because any leading tab or space characters
would appear in the displayed text.
<?xml version="1.0"?>
<!-- textcontrols/TextCDATA.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="500">
<mx:Text width="100%">
<mx:text>
<![CDATA[This string contains a less than, <, greater than, >,
ampersand, &, apostrophe, ', return,
tab. and quotation mark, ".]]>
</mx:text>
</mx:Text>
</mx:Application>
The displayed text appears on three lines, as follows:
This string contains a less than, <, greater than, >,
ampersand, &, apostrophe, ', return,
tab. and quotation mark, ".
Specifying special characters in ActionScript
The following rules specifying how to include special characters in a text control when you
specify the control’s text property value in ActionScript, for example, in an initialization
function, or when assigning a string value to a variable that you use to populate the property.
■
You cannot use the character that encloses the text string inside the string. If you surround
the string in double-quotation marks ("), use the escape sequence \" for any doublequotation marks in the string. If you surround the string in single-quotation marks ('), use
the escape sequence \' for any single-quotation marks in the string.
■
Use backslash escape characters for special characters, including \t for the tab character,
and \n or \r for a return/line feed character combination. You can use the escape character
\" for the double-quotation mark and \' for the single-quotation mark.
■
In standard text, but not in CDATA sections, you can use the special characters left angle
bracket (<), right angle bracket (>), and ampersand (&), by inserting the XML character
entity equivalents of &lt;, &gt;, and &amp;, respectively. You can also use &quot; and
&apos; for double-quotation marks ("), and single-quotation marks ('), and you can use
numeric character references, such as &#165; for the Yen mark (¥). Do not use any other
named character entities; Flex treats them as literal text.
■
In CDATA sections only, do not use character entities or references, such as &lt; or
&#165; because Flex treats them as literal text. Instead, use the actual character, such as <.
374
Using Text Controls
The following example uses an initialization function to set the text property to a string that
contains these characters:
<?xml version="1.0"?>
<!-- textcontrols/InitText.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="initText()">
<mx:Script>
public function initText():void {
//The following is on one line.
myText.text="This string contains a return, \n, tab, \t, and
quotation mark, \". This string also contains less than, &lt;, greater than,
&gt;, ampersand, &amp;, and apostrophe, ', characters.";
}
</mx:Script>
<mx:Text width="450" id="myText" initialize="initText();"/>
</mx:Application>
The following example uses an <mx:Script> tag with a variable in a CDATA section to set
the text property:
<?xml version="1.0"?>
<!-- textcontrols/VarText.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
[Bindable]
//The following is on one line.
public var myText:String ="This string contains a return, \n, tab, \t,
and quotation mark, \". This string also contains less than, <, greater
than, <, ampersand, <;, and apostrophe, ', characters.";
]]>
</mx:Script>
<mx:Text width="450" text="{myText}"/>
</mx:Application>
The displayed text for each example appears on three lines. The first line ends at the return
specified by the \n character. The remaining text wraps onto a third line because it is too long
to fit on a single line. (Note: Although the tab character may be noticeable in the following
output, it is included in the right location.)
This string contains a return,
, tab, , and quotation mark, ". This string also contains less than, <,
greater than, >, ampersand, &, and apostrophe, ', characters.
Using the text property
375
Using the htmlText property
You use the htmlText property to set or get an HTML-formatted text string. You can also use
one tag that is not part of standard HTML, the textFormat tag. For details of supported tags
and attributes, see “Using tags in HTML text” on page 380.
You can also specify text formatting using Flex styles. You can set a base style, such as the font
characteristics or the text weight using a style, and override the base style in sections of your
text by using tags, such as the <font> tag. In the following example, the <mx:Text> tag styles
specify blue, italic, 14 point text, and the <mx:htmlText> tag includes HTML tags that
override the color and point size.
<?xml version="1.0"?>
<!-- textcontrols/HTMLTags.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="450"
backgroundGradientColors="[#FFFFFF, #FFFFFF]">
<mx:Text width="100%" color="blue" fontStyle="italic" fontSize="14">
<mx:htmlText>
<![CDATA[This is 14 point blue italic text.<br><b><font
color="#000000" size="10">This text is 10 point black, italic, and bold.</
font></b>]]>
</mx:htmlText>
</mx:Text>
</mx:Application>
This code results in the following output:
Specifying HTML tags and text
To prevent the Flex compiler from generating errors when it encounters HTML tags in the
text, use one of the following techniques:
■
Wrap your text in a CDATA tag.
■
Specify HTML markup by using the &lt;, &gt;, and &amp; character entities in place of
the left angle bracket (<), right angle bracket (>), and ampersand (&) HTML delimiters.
Adobe recommends using CDATA sections for all but simple HTML markup, because the
character entity technique has significant limitations:
■
Extensive HTML markup can be cumbersome to write and difficult to read.
■
You must use a complex escape sequence to include the less than and ampersand
characters in your text.
376
Using Text Controls
For example, to display the following string:
A less than character < and bold text.
without using a CDATA section, you must use the following text:
A less than character &amp;c#060; and &lt;b&gtbold text&lt;/b&gt.
In a CDATA section, you use the following text:
A less than character &lt; and <b>bold text</b>.
Specifying HTML text
When you specify HTML text for a text control, the following rules apply:
■
You cannot use a CDATA section directly in an inline htmlText property in an
<mx:Text> tag. You must put the text in an <mx:htmlText> subtag, or in ActionScript
code.
■
Flex collapses consecutive white space characters, including return, space, and tab
characters, in text that you specify in MXML property assignments or ActionScript
outside of a CDATA section.
■
If you specify the text in a CDATA section, you can use the text control’s condenseWhite
property to control whether Flex collapses white space. By default, the condenseWhite
property is false, and Flex does not collapse white space.
■
Use HTML <p> and <br> tags for breaks and paragraphs. In ActionScript CDATA
sections You can also use \n escape characters.
■
If your HTML text string is surrounded by single- or double-quotation marks because it is
in an assignment statement (in other words, if it is not in an <mx:htmlText> tag), you
must escape any uses of that quotation character in the string:
■
If you use double-quotation marks for the assignment delimiters, use &quot; for the
double-quotation mark (") character in your HTML. In ActionScript, you can also use
the escape sequence \".
N O TE
■
You do not need to escape double-quotation marks if you’re loading text from an
external file; it is only necessary if you’re assigning a string of text in ActionScript.
If you use single-quotation marks for the assignment delimiters, use &apos; for the
single-quotation mark character (') in your HTML. In ActionScript, you can also use
the escape sequence \’.
Using the htmlText property
377
■
When you enter HTML-formatted text, you must include attributes of HTML tags in
double- or single-quotation marks. Attribute values without quotation marks can produce
unexpected results, such as improper rendering of text. You must follow the escaping rules
for quotation marks within quotation marks, as described in “Escaping special characters
in HTML text” on page 379.
The following example shows some simple HTML formatted text, using MXML and
ActionScript to specify the text:
<?xml version="1.0"?>
<!-- textcontrols/HTMLFormattedText.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="500">
<mx:Script><![CDATA[
//The following is on one line.
[Bindable]
public var myHtmlText:String="This string contains <b>less than </b>,
&lt;, <b>greater than</b>, &gt;, <b>ampersand</b>, &amp;, and <b>double
quotation mark</b>, &quot;, characters.";
]]></mx:Script>
<mx:Text id="htmltext2" width="450" htmlText="{myHtmlText}" />
<mx:Text width="450">
<mx:htmlText>
<!-- The following is on one line. Line breaks would appear in the
output. -->
<![CDATA[
This string contains <b>less than</b>, &lt;, <b>greater than </
b>, &gt;, <b>ampersand</b>, &amp;, and <b>double quotation mark</b>,&quot;,
characters.
]]>
</mx:htmlText>
</mx:Text>
</mx:Application>
Each Text control displays the following text:
This string contains less than, <, greater than, >, ampersand, &, and double
quotation mark, " characters.
378
Using Text Controls
Escaping special characters in HTML text
The rules for escaping special characters in HTML text differ between CDATA sections and
standard text.
In CDATA sections
When you specify the htmlText string, the following rules apply:
■
In ActionScript, but not in an <mx:htmlText> tag, you can use standard backslash escape
sequences for special characters, such as \t for tab and \n for a newline character. You can
also use the backslash character to escape many special characters, such as \’ and \" for
single- and double-quotation marks. You cannot use the combination \<, and a backslash
before a return character has no effect on displayed text; it allows you to break the
assignment statement across multiple text lines.
■
In both ActionScript and the <mx:htmlText> tag, you can use HTML tags and numeric
character entities; for example in place of \n, you can use a <br> tag.
■
To include a left angle bracket (<), right angle bracket (>), or ampersand (&) character in
displayed text, use the corresponding character entities: &lt;, &gt;, and &amp;,
respectively. You can also use the &quot; and &apos; entities for single- and doublequotation marks. These are the only named character entities that Flash Player recognizes.
Flash Player recognizes numeric entities, such as &#165; for the Yen mark (¥), however, it
does not recognize the corresponding character entity, &yen;.
The following code example uses the htmlText property to display formatted text:
<?xml version="1.0"?>
<!-- textcontrols/HTMLTags2.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="500">
<mx:Text width="100%">
<mx:htmlText><![CDATA[<p>This string contains a <b>less than</b>, &lt;.
</p><p>This text is in a new paragraph.<br>This is a new line.</
p>]]>
</mx:htmlText>
</mx:Text>
</mx:Application>
This code displays the following text:
This string contains a less than, <.
This text is in a new paragraph.
This is a new line.
In standard text
■
The following rules apply:
You must use character entities, as described in “Using the htmlText property”
on page 376, to use the left angle bracket (<), right angle bracket (>), or ampersand (&)
character in HTML; for example, when you open a tag or start a character entity.
Using the htmlText property
379
■
You must use the &amp; named entity combined with an HTML numeric character entity
to display the less than character (use &amp;#060;) and ampersand character (use
&amp;#038;). You can use the standard character entities, &gt;, &quot;, and &apos;, for
the greater than, double-quotation mark and single-quotation mark characters,
respectively. For all other character entities, use numeric entity combinations, such as
&amp;#165;, for the Yen mark (¥).
■
In ActionScript, but not in an <mx:htmlText> tag or inline htmlText property, you can
use a backslash character to escape special characters, including the tab, newline, and
quotation mark characters (but not the ampersand). In all cases, you can use (properly
escaped) HTML tags and numeric character entities; for example in place of \n, you can
use a &lt;br&gt; tag or &amp;#013; entity.
Using tags in HTML text
When you use the htmlText property, you use a subset of HTML that is supported by the
Flash Player. The Flash Player supports the following tags:
■
Anchor tag (<a>)
■
Bold tag (<b>)
■
Break tag (<br>)
■
Font tag (<font>)
■
Image tag (<img>)
■
Italic tag (<i>)
■
List item tag (<li>)
■
Paragraph tag (<p>)
■
Text format tag (<textformat>)
■
Underline tag (<u>)
Anchor tag (<a>)
The anchor <a> tag creates a hyperlink and supports the following attributes:
Specifies the URL of the page to load in the browser. The URL can be absolute or
relative to the location of the SWF file that is loading the page.
href
target
Specifies the name of the target window to load the page into.
For example, the following HTML snippet creates the link “Go Home” to the Adobe Web
site.
<a href='http://www.adobe.com' target='_blank'>Go Home</a>
380
Using Text Controls
You can also define a:link, a:hover, and a:active styles for anchor tags by using style
sheets.
The <a> tag does not make the link text blue. You must apply formatting tags to change the
text format. You can also define a:link, a:hover, and a:active styles for anchor tags by
using style sheets.
The Label, Text, and TextArea controls can dispatch a link event when the user selects a
hyperlink in the htmlText property. To generate the link event, prefix the hyperlink
destination with event:, as the following example shows:
<?xml version="1.0"?>
<!-- textcontrols/LabelControlLinkEvent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
borderStyle="solid"
backgroundGradientColors="[#FFFFFF, #FFFFFF]">
<mx:Script>
<![CDATA[
import flash.events.TextEvent;
public function linkHandler(event:TextEvent):void {
myTA.text="link occured.";
// Open the link in a new window.
navigateToURL(new URLRequest(event.text), '_blank')
}
]]>
</mx:Script>
<mx:Label selectable="true" link="linkHandler(event);">
<mx:htmlText><![CDATA[<a href='event:http://www.adobe.com'>Adobe</
a>]]></mx:htmlText>
</mx:Label>
<mx:TextArea id="myTA"/>
</mx:Application>
The Label control must have the selectable property set to true to generate the link event.
When you use the link event, the event is generated and the text following event: in the
hyperlink destination is included in the text property of the event object. However, the
hyperlink is not automatically executed; you must execute the hyperlink from within your
event handler. This allows you to modify the hyperlink, or even prohibit it from occurring, in
your application.
Using the htmlText property
381
Bold tag (<b>)
The bold <b> tag renders text as bold. If you use embedded fonts, a boldface font must be
available for the font or no text appears. If you use fonts that you expect to reside on the local
system of your users, their system may approximate a boldface font if none exists, or it may
substitute the normal font face instead of boldface. In either case, the text inside the bold tags
will appear.
The following snippet applies boldface to the word bold:
This word is <b>bold</b>.
You cannot use the </b> end tag to override bold formatting that you set for all text in a
control by using the fontWeight style.
Break tag (<br>)
The break <br> tag creates a line break in the text. This tag has no effect in Label or TextInput
controls.
The following snippet starts a new line after the word line:
The next sentence is on a new line.<br>Hello there.
Font tag (<font>)
The <font> tag specifies the following font characteristics: color, face, and size.
The font tag supports the following attributes:
Specifies the text color. You must use hexadecimal (#FFFFFF) color values. Other
formats are not supported.
color
Specifies the name of the font to use. You can also specify a list of comma-separated
font names, in which case Flash Player chooses the first available font. If the specified font is
not installed on the playback system, or isn’t embedded in the SWF file, Flash Player chooses
a substitute font. The following example shows how to set the font face.
face
size
Specifies the size of the font in points. You can also use relative sizes (for example, +2
or -4).
382
Using Text Controls
The following example shows the use of the <font> tag:
<?xml version="1.0"?>
<!-- textcontrols/FontTag.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
backgroundGradientColors="[#FFFFFF, #FFFFFF]">
<mx:TextArea height="100" width="250">
<mx:htmlText>
<![CDATA[
You can vary the <font size='20'>font size</font>,<br><font
color="#0000FF">color</font>,<br><font face="CourierNew, Courier,
Typewriter">face</font>, or<br><font size="18" color="#FF00FF"face="Times,
Times New Roman, _serif">any combination of the three.</font>
]]>
</mx:htmlText>
</mx:TextArea>
</mx:Application>
This code results in the following output:
Image tag (<img>)
NO T E
The <img> tag is not fully supported in Flex 2, and might not work in some cases.
The image <img> tag lets you embed external JPEG, GIF, PNG, and SWF files inside text
fields. Text automatically flows around images you embed in text fields. This tag is supported
only in dynamic and input text fields that are multiline and wrap their text.
By default, Flash displays media embedded in a text field at full size. To specify dimensions for
embedded media, use the <img> tag’s height and width attributes.
In general, an image embedded in a text field appears on the line following the <img> tag.
However, when the <img> tag is the first character in the text field, the image appears on the
first line of the text field.
The <img> tag has one required attribute, src, which specifies the path to an image file. All
other attributes are optional.
Using the htmlText property
383
The <img> tag supports the following attributes:
Specifies the URL to a GIF, JPEG, PNG, or SWF file. This attribute is required; all
other attributes are optional. External files are not displayed until they have downloaded
completely.
src
align Specifies the horizontal alignment of the embedded image within the text field. Valid
values are left and right. The default value is left.
height
Specifies the height of the image, in pixels.
Specifies the amount of horizontal space that surrounds the image where no text
appears. The default value is 8.
hspace
id Specifies the identifier for the imported image. This is useful if you want to control the
embedded content with ActionScript.
vspace
width
Specifies the amount of vertical space that surrounds the image where no text.
Specifies the width of the image, in pixels.
appears. The default value is 8.
The following example shows the use of the <img> tag and how text can flow around the
image:
<?xml version="1.0"?>
<!-- textcontrols/ImgTag.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
backgroundGradientColors="[#FFFFFF, #FFFFFF]" width="300" height="300">
<mx:Text height="100%" width="100%">
<mx:htmlText>
<![CDATA[
<p>You can include an image in your HTML text with the &lt;img&gt;
tag.</p><p><img src='../assets/bird.gif' width='30' height='30'
align='left' hspace='10' vspace='10'>Here is text that follows the image.
I'm extending the text by lengthening this sentence until it's long enough
to show wrapping around the bottom of the image.</p>
]]>
</mx:htmlText>
</mx:Text>
</mx:Application>
This code results in the following output:
384
Using Text Controls
Making hyperlinks out of embedded images
To make a hyperlink out of an embedded image, enclose the <img> tag in an <a> tag, as the
following example shows:
<?xml version="1.0"?>
<!-- textcontrols/ImgTagWithHyperlink.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="500"
height="500" borderStyle="solid">
<mx:TextArea width="100%" height="100%">
<mx:htmlText>
<![CDATA[
<a href='http://www.adobe.com'><img src='../assets/bird.gif'/></
a>Click the image to go to the Adobe home page.
]]>
</mx:htmlText>
</mx:TextArea>
</mx:Application>
When the user moves the mouse pointer over an image that is enclosed by <a> tags, the mouse
pointer changes to a hand icon, as with standard hyperlinks. Interactivity, such as mouse clicks
and key presses, do not register in SWF files that are enclosed by <a> tags.
Italic tag (<i>)
The italic <i> tag displays the tagged text in italic font. If you’re using embedded fonts, an
italic font must be available or no text appears. If you use fonts that you expect to reside on
the local system of your users, their system may approximate an italic font if none exists, or it
may substitute the normal font face instead of italic. In either case, the text inside the italic
tags appears.
The following snippet applies italic font to the word italic:
The next word is in <i>italic</i>.
You cannot use the </i> end tag to override italic formatting that you set for all text in a
control by using the fontStyle style.
Using the htmlText property
385
List item tag (<li>)
The list item <li> tag ensures that the text that it encloses starts on a new line with a bullet in
front of it. You cannot use it for any other type of HTML list item. The ending </li> tag
ensures a line break (but </li><li> generates a single line break). Unlike in HTML, you do
not surround <li> tags in <ul> tags. For example, the following Flex code generates a
bulleted list with two items:
<?xml version="1.0"?>
<!-- textcontrols/BulletedListExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="500">
<mx:Text width="100%">
<mx:htmlText >
<![CDATA[
<p>This is a bulleted list:<li>First Item</li><li>Second Item</
li></p>
]]>
</mx:htmlText>
</mx:Text>
</mx:Application>
N OT E
In Flex 2, the <li> tag does not work properly with Label controls. With TextInput
controls, it must be put before the first character in the text.
Paragraph tag (<p>)
The paragraph <p> tag creates a new paragraph. The opening <p> tag does not force a line
break, but the closing </p> tag does. Unlike in HTML, the <p> tag does not force a double
space between paragraphs; the spacing is the same as that generated by the <br> tag.
The <p> tag supports the following attribute:
Specifies alignment of text in the paragraph; valid values are left, right,
and center.
align
The following snippet generates two centered paragraphs:
<p align="center">This is a first centered paragraph</p>
<p align="center">This is a second centered paragraph</p>
Text format tag (<textformat>)
The text format <textformat> tag lets you use a subset of paragraph formatting properties of
the TextFormat class in HTML text fields, including line leading, indentation, margins, and
tab stops. You can combine text format tags with the built-in HTML tags. The text format tag
supports the following attributes:
■
blockindent
<textformat>
386
Specifies the indentation, in points, from the left margin to the text in the
tag body.
Using Text Controls
Specifies the indentation, in points, from the left margin or the block indent, if
any, to the first character in the <textformat> tag body.
■
indent
■
leading
■
leftmargin
■
rightmargin
■
tabstops
Specifies the amount of leading (vertical space) between lines.
Specifies the left margin of the paragraph, in points.
Specifies the right margin of the paragraph, in points.
Specifies custom tab stops as an array of nonnegative integers.
Underline tag (<u>)
The underline <u> tag underlines the tagged text.
The following snippet underlines the word underlined:
The next word is <u>underlined</u>.
You cannot use the </u> end tag to override underlining that you set for all text in a control
by using the textDecoration style.
Selecting and modifying text
You can select and modify text in TextArea, TextInput and RichTextEditor controls, as
described in the following sections. (To change a Label or Text control’s text, assign a new
value to the control’s text or HTMLtext property. For more information on the HTMLText
property, see “Using the htmlText property” on page 376.
Selecting text
The Flex editable controls provide properties and methods to select text regions and get
selections, as the following sections describe. You can modify the contents of the selection as
described in “Modifying text” on page 388.
Creating a selection
The TextInput and TextArea controls, including the RichTextEditor control’s TextArea
subcontrol, provide the following text selection properties and method:
■
setSelection() method selects a range of text. You specify the zero-based indexes of the
start character and the position immediately after the last character in the text.
■
selectionBeginIndex
and selectionEndIndex set or return the zero-based location in
the text of the start and position immediately after the end of a selection.
Selecting and modifying text
387
To select the first 10 characters of the myTextArea TextArea control, for example, use the
following method:
myTextArea.setSelection(0, 10);
To change the last character of this selection to be the twenty-fifth character in the TextArea
control, use the following statement:
myTextArea.endIndex=25;
To select text in a RichTextEditor control, use the control’s TextArea subcontrol, which you
access by using the textArea id. To select the first 10 characters in the myRTE
RichTextEditor control, for example, use the following code:
myRTE.textArea.setSelection(0, 10);
Getting a selection
You get a text control’s selection by getting a TextRange object with the selected text. You can
then use the TextRange object to modify the selected text, as described in “Modifying text”
on page 388. The technique you use to get the selection depends on the control type, as the
following sections describe.
To get the selection in a TextArea or TextInput control
Use the TextRange class constructor to get a TextRange object with the currently selected text
in a TextArea or TextInput control. For example, to get the current selection of the
myTextArea control, use the following line:
var mySelectedTextRange:TextRange = new TextRange(myTextArea, true);
The second parameter, true, tells the constructor to return a TextRange object with the
selected text.
To get the selection in a RichTextEditor control
Use the selection read-only property of the RichTextEditor to get a TextRange object with
the currently selected text in its TextArea subcontrol. You can use the TextRange object to
modify the selected text, as described in “Modifying text”. For example, to get the current
selection of the MyRTE RichTextEditor control, us the following line:
public var mySelectedTextRange:TextRange = myRTE.selection;
Modifying text
You use the TextRange class to modify the text in a TextArea, TextInput, or RichTextEditor
control. This class lets you affect the following text characteristics:
■
text
388
or htmltext property contents
Using Text Controls
■
text color, decoration (underlining), and alignment
■
font family, size, style (italics), and weight (bold)
■
URL of an HTML <a> link.
Getting a TextRange object
To get a TextRange object you use the following techniques:
■
Get a TextRange object that contains the current text selection, as described in “Getting a
selection” on page 388.
■
Create a TextRange object that contains a specific range of text.
To create a TextRange object with a specific range of text, use a TextRange constructor with
the following format:
new TextRange(control, modifiesSelection, beginIndex, endIndex)
Specify the control that contains the text, whether the TextRange object corresponds to a
selection (that is, represents and modifies selected text), and the zero-based indexes in the text
of the first and last character of the range. As a general rule, do not use the TextRange
constructor to set a selection; use the setSelection() method, as described in “Creating a
selection” on page 387. For this reason, the second parameter should always be false when
you specify the begin and end indexes.
To get a TextRange object with the fifth through twenty-fifth characters of a TextArea control
named myTextArea, for example, use the following line:
var myTARange:TextRange = new TextRange(myTextArea, false, 4, 25);
Changing text
After you get a TextRange object, use its properties to modify the text in the range. The
changes you make to the TextRange appear in the text control.
Selecting and modifying text
389
You can get or set the text in a TextRange object as HTML text or as a plain text, independent
of any property that you might have used to initially set the text. If you created a TextArea
control, for example, and set its text property, you can use the TextRange htmlText property
to get and change the text. The following example shows this usage, and shows using the
TextRange class to access a range of text and change its properties. It also shows using String
properties and methods to get text indexes.
<?xml version="1.0"?>
<!-- textcontrols/TextRangeExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="600"
height="500">
<mx:Script><![CDATA[
import mx.controls.textClasses.TextRange
public function alterText():void {
// Create a TextRange object starting with "the" and ending at the
// first period. Replace it with new formatted HTML text.
var tr1:TextRange = new TextRange(ta1, false,
ta1.text.indexOf("the", 0), ta1.text.indexOf(".", 0));
tr1.htmlText="<i>italic HTML text</i>"
// Create a TextRange object with the remaining text.
// Select the text and change its formatting.
var tr2:TextRange = new TextRange(ta1, true, ta1.text.indexOf("It",
0), ta1.text.length-1);
tr2.color=0xFF00FF;
tr2.fontSize=18;
tr2.fontStyle = "italic"; // any other value turns italic off
tr2.fontWeight = "bold"; // any other value turns bold off
ta1.setSelection(0, 0);
}
]]></mx:Script>
<mx:TextArea id="ta1" fontSize="12" fontWeight="bold" width="100%"
height="100">
<mx:text>
This is a test of the emergency broadcast system. It is only a test.
</mx:text>
</mx:TextArea>
<mx:Button label="Alter Text" click="alterText();"/>
</mx:Application>
390
Using Text Controls
Example: changing selected text in a RichTextEditor
control
The following example shows how you can use the selectedText property of the
RichTextEditor control to get a TextRange when a user selects some text, and use TextRange
properties to get and change the characteristics of the selected text. To use the example, select
a range of text with your mouse. When you release the mouse button, the string “This is
replacement text. ”, formatted in fuchsia Courier 20-point font replaces the selection and the
text area reports on the original and replacement text.
<?xml version="1.0"?>
<!-- textcontrols/TextRangeSelectedText.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="600"
height="500">
<mx:Script><![CDATA[
import mx.controls.textClasses.TextRange;
//The following text must be on a single line.
[Bindable]
public var htmlData:String="<textformat leading='2'><p
align='center'><b><font size='20'>HTML Formatted Text</font></b></p></
textformat><br><textformat leading='2'><p align='left'><font face='_sans'
size='12' color='#000000'>This paragraph contains <b>bold</b>, <i>italic</
i>, <u>underlined</u>, and <b><i><u>bold italic underlined </u></i></
b>text. </font></p></textformat><br><p><u><font face='arial' size='14'
color='#ff0000'>This a red underlined 14-point arial font with no alignment
set.</font></u></p><p align='right'><font face='verdana' size='12'
color='#006666'><b>This a teal bold 12-pt. Verdana font with alignment set
to right.</b></font></p>";
public function changeSelectionText():void {
//Get a TextRange with the selected text and find its length.
var sel:TextRange = rte1.selection;
var selLength:int = sel.endIndex - sel.beginIndex;
//Do the following only if the user made a selection.
if (selLength) {
//Display the selection size and font color, size, and family.
t1.text="Number of characters selected: " + String(selLength);
t1.text+="\n\nOriginal Font Family: " + sel.fontFamily;
t1.text+="\nOriginal Font Size: " + sel.fontSize;
t1.text+="\nOriginal Font Color: " + sel.color;
//Change font color, size, and family and replace selected text.
sel.text="This is replacement text. "
sel.color="fuchsia";
sel.fontSize=20;
sel.fontFamily="courier"
//Show the new font color, size, and family.
t1.text+="\n\nNew text length: " + String(sel.endIndex -
Selecting and modifying text
391
sel.beginIndex);
t1.text+="\nNew Font Family: " + sel.fontFamily;
t1.text+="\nNew Font Size: " + sel.fontSize;
t1.text+="\nNew Font Color: " + sel.color;
}
}
]]></mx:Script>
<!-- The text area. When you release the mouse after selecting text,
it calls the func1 function. -->
<mx:RichTextEditor id="rte1" htmlText="{htmlData}" width="100%"
height="100%" mouseUp="changeSelectionText()"/>
<mx:TextArea editable="false" id="t1" fontSize="12" fontWeight="bold"
width="300" height="180"/>
</mx:Application>
Label control
The Label control is a noneditable single-line text label. It has the following characteristics:
■
The user cannot change the text, but the application can modify it.
■
You can specify text formatting by using styles or HTML text.
■
You can control the alignment and sizing.
■
The control is transparent and does not have a backgroundColor property, so the
background of the component’s container shows through.
■
The control has no borders, so the label appears as text written directly on its background.
■
The control cannot take the focus.
For complete reference information, see Label in Adobe Flex 2 Language Reference.
To create a multiline, noneditable text field, use a Text control. For more information, see
“Text control” on page 395. To create user-editable text fields, use TextInput or TextArea
controls. For more information, see “TextInput control” on page 393 and “TextArea control”
on page 397.
The following image shows a Label control:
For the code used to create this sample, see “Creating a Label control”.
392
Using Text Controls
Creating a Label control
You define a Label control in MXML by using the <mx:Label> 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 an ActionScript block.
<?xml version="1.0"?>
<!-- textcontrols/LabelControl.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="150"
height="80" borderStyle="solid" backgroundGradientColors="[#FFFFFF,
#FFFFFF]">
<mx:Label text="Label1"/>
</mx:Application>
You use the text property to specify a string of raw text, and the htmlText property to
specify an HTML-formatted string. For more information on using these properties, see
“Using the text property” on page 371 and “Using the htmlText property” on page 376.
Sizing a Label control
The Label control has the following default sizing properties:
Property
Default value
Default size
Width and height large enough for the text
Minimum size
0
Maximum size
10000 by 10000 pixels
If you do not specify a width, the Label control automatically resizes when you change the
value of the text or htmlText property.
If you explicitly size a Label control so that it is not large enough to accommodate its text, the
text is truncated and terminated by an ellipses (...). The full text displays as a tooltip when you
move the mouse over the Label control. If you also set a tooltip by using the tooltip
property, the tooltip is displayed rather than the text.
TextInput control
The TextInput control is a single-line text field that is optionally editable. The TextInput
control supports the HTML rendering capabilities of Adobe Flash Player.
For complete reference information, see TextInput in Adobe Flex 2 Language Reference.
TextInput control
393
The following image shows a TextInput control:
To create a multiline, editable text field, use a TextArea control. For more information, see
“TextArea control” on page 397. To create noneditable text fields, use Label and Text
controls. For more information, see “Label control” on page 392 and “Text control”
on page 395.
The TextInput control does not include a label, but you can add one using a Label control or
by nesting the TextInput control in a FormItem container in a Form layout container, as
shown in the example in “About text controls” on page 369. TextInput controls dispatch
change, textInput, and enter events.
If you disable a TextInput control, it displays its contents in a different color, represented by
the disabledColor style. You can set a TextInput control’s editable property to false to
prevent editing of the text. You can set a TextInput control’s displayAsPassword property to
conceal the input text by displaying characters as asterisks.
Creating a TextInput control
You define a TextInput control in MXML using the <mx:TextInput> tag, as the following
example shows. Specify an id value if you intend to refer to a control elsewhere in your
MXML, either in another tag or in an ActionScript block.
<?xml version="1.0"?>
<!-- textcontrols/TextInputControl.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:TextInput id="text1" width="100"/>
</mx:Application>
Just as you can for the Label control, you use the text property to specify a string of raw text,
and the htmlText property to specify an HTML-formatted string. For more information, see
“Using the text property” on page 371 and “Using the htmlText property” on page 376.
Sizing a TextInput control
The TextInput control has the following default sizing properties:
Property
Default value
Default size
The size of the text with a default minimum size of 22 pixels high and 160
pixels wide
394
Using Text Controls
Property
Default value
Minimum size
0
Maximum size
10000 by 10000 pixels
If you do not specify a width, the TextInput control automatically resizes when you change
the value of the text or htmlText property. It does not resize in response to typed user input.
Binding to a TextInput control
In some cases, you might want to bind a variable to the text property of a TextInput control so
that the control represents a variable value, as the following example shows:
<?xml version="1.0"?>
<!-- textcontrols/BoundTextInputControl.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
[Bindable]
public var myProp:String="This is the initial myPropString.";
]]></mx:Script>
<mx:TextInput text="{myProp}"/>
</mx:Application>
In this example, the TextInput control displays the value of the myProp variable. Remember
that you must use the [Bindable] metadata tag if the variable changes value and the control
must track the changed values; also, the compiler generates warnings if you do not use this
metadata tag.
Text control
The Text control displays multiline, noneditable text. The control has the following
characteristics:
■
The user cannot change the text, but the application can modify it.
■
The control does not support scroll bars. If the text exceeds the control size users can use
keys to scroll the text
■
The control is transparent so that the background of the component’s container shows
through
■
The control has no borders, so the label appears as text written directly on its background.
■
The control supports HTML text and a variety of text and font styles.
■
The text always word-wraps at the control boundaries, and is always aligned to the top of
the control.
Text control
395
For complete reference information, see Text in Adobe Flex 2 Language Reference.
To create a single-line, noneditable text field, use the Label control. For more information, see
“Label control” on page 392. To create user-editable text fields, use the TextInput or TextArea
controls. For more information, see “TextInput control” on page 393 and “TextArea control”
on page 397.
The following image shows an example of a Text control with a with of 175 pixels:
Creating a Text control
You define a Text control in MXML using the <mx:Text> 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"?>
<!-- textcontrols/TextControl.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Text width="175" text="This is an example of a multiline text string
in a Text control."/>
</mx:Application>
You use the text property to specify a string of raw text, and the htmlText property to
specify an HTML-formatted string. For more information, see “Using the text property”
on page 371 and “Using the htmlText property” on page 376.
This control does not support a backgroundColor property; its background is always the
background of the control’s container.
Sizing a Text control
The Text control has the following default sizing properties:
Property
Default value
Default size
Flex sizes the control to fit the text, with the control width is long enough to fit
the longest line of text, and the height tall enough to fit the number of lines. If
you do not specify a pixel width, the height is determined by the number of
explicit line breaks in the text string. If the text length changes, the control
resizes to fit the new text.
Minimum size 0
Maximum size 10000 by 10000 pixels
396
Using Text Controls
Flex sizes the Text control as follows:
■
If you specify a pixel value for both the height and width properties, any text that
exceeds the size of the control is clipped at the border.
■
If you specify an explicit pixel width, but no height, Flex wraps the text to fit the width
and calculates the height to fit the required number of lines.
■
If you specify a percentage-based width and no height, Flex does not wrap the text, and the
height equals the number of lines as determined by the number of Return characters.
■
If you specify only a height and no width, the height value does not affect the width
calculation, and Flex sizes the control to fit the width of the maximum line.
As a general rule, if you have long text, you should specify a pixel-based width property. If the
text might change and you want to ensure that the Text control always takes up the same
space in your application, set explicit height and width properties that fit the largest
expected text.
TextArea control
The TextArea control is a multiline, editable text field with a border and optional scroll bars.
The TextArea control supports the HTML and rich text rendering capabilities of Flash Player.
The TextArea control dispatches change and textInput events.
For complete reference information, see TextArea in Adobe Flex 2 Language Reference.
The following image shows a TextArea control:
To create a single-line, editable text field, use the TextInput control. For more information,
see “TextInput control” on page 393. To create noneditable text fields, use the Label and Text
controls. For more information, see “Label control” on page 392 and “Text control”
on page 395.
If you disable a TextArea control, it displays its contents in a different color, represented by
the disabledColor style. You can set a TextArea control’s editable property to false to
prevent editing of the text. You can set a TextArea control’s displayAsPassword property to
conceal input text by displaying characters as asterisks.
TextArea control
397
Creating a TextArea control
You define a TextArea control in MXML using the <mx:TextArea> tag, as the following
example shows. Specify an id value if you intend to refer to a control elsewhere in your
MXML, either in another tag or in an ActionScript block.
<?xml version="1.0"?>
<!-- textcontrols/TextAreaControl.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:TextArea id="textConfirm" width="300" height="100" text="Please enter
your thoughts here."/>
</mx:Application>
Just as you can for the Text control, you use the text property to specify a string of raw text,
and the htmlText property to specify an HTML-formatted string. For more information, see
“Using the text property” on page 371 and “Using the htmlText property” on page 376.
Sizing the TextArea control
The TextArea control has the following default sizing properties:
Property
Default value
Default size
160 pixels for the width property
44 pixels for the height property
Minimum size
0
Maximum size
10000 by 10000 pixels
The TextArea control does not resize to fit the text that it contains. If the new text exceeds the
capacity of the TextArea control and the horizontalScrollPolicy is true (the default
value), the control adds a scrollbar.
RichTextEditor control
The RichTextEditor control lets users enter, edit, and format text. Users apply text formatting
and URL links using subcontrols that are located at the bottom of the RichTextEditor
control.
For complete reference information, see RichTextEditor in Adobe Flex 2 Language Reference.
398
Using Text Controls
About the RichTextEditor control
The RichTextEditor control consists a Panel control with two direct children:
■
A TextArea control in which users can enter text
■
A tool bar container with format controls that let a user specify the text characteristics.
Users can use the tool bar subcontrols to apply the following text characteristics:
■
Font family
■
Font size
■
Any combination of bold, italic and underline font styles
■
Text color
■
Text alignment: left, center, right, or justified
■
Bullets
■
URL links
The following image shows a RichTextEditor control with some formatted text:
For the source for this example, see “Creating a RichTextEditor control” on page 400.
You use the RichTextEditor interactively as follows:
■
Text that you type is formatted as specified by the control settings.
■
To apply new formatting to existing text, select the text and set the controls to the
required format.
■
To create a link, select a range of text, enter the link target in the text box on the right, and
press Enter. You can only specify the URL; the link always opens in a _blank target. Also,
creating the link does not change the appearance of the link text; you must separately
apply any color and underlining.
RichTextEditor control
399
■
You can cut, copy, and paste rich text within and between Flash HTML text fields,
including the RichTextEditor control’s TextArea subcontrol, using the normal keyboard
commands. You can copy and paste plain text between the TextArea and any other text
application, such as your browser or a text editor.
Creating a RichTextEditor control
You define a RichTextEditor control in MXML using the <mx:RichTextEditor> tag, as the
following example shows. Specify an id value if you intend to refer to a control elsewhere in
your MXML, either in another tag or in an ActionScript block.
<?xml version="1.0"?>
<!-- textcontrols/RichTextEditorControl.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:RichTextEditor id="myRTE" text="Congratulations, winner!" />
</mx:Application>
You can use the text property to specify an unformatted text string, or the htmlText
property to specify an HTML-formatted string. For more information on using these
properties, see “Using the text property” on page 371, and “Using the htmlText property”
on page 376. For information on selecting, replacing, and formatting text that is in the
control, see “Selecting and modifying text” on page 387.
400
Using Text Controls
The following example shows the code used to create the image in “About the RichTextEditor
control” on page 399:
<?xml version="1.0"?>
<!-- textcontrols/RichTextEditorControlWithFormattedText.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="700"
height="400">
<!-- The HTML text string used to populate the RichTextEditor control's
TextArea subcontrol. The text is on a single line. -->
<mx:Script><![CDATA[
[Bindable]
public var htmlData:String="<textformat leading='2'><p
align='center'><b><font size='20'>HTML Formatted Text</font></b></p></
textformat><br><textformat leading='2'><p align='left'><font face='_sans'
size='12' color='#000000'>This paragraph contains<b>bold</b>, <i>italic</
i>, <u>underlined</u>, and <b><i><u>bold italic underlined </u></i></
b>text.</font></p></textformat><br><p><u><font face='arial' size='14'
color='#ff0000'>This a red underlined 14-point arial font with no alignment
set.</font></u></p><p align='right'><font face='verdana' size='12'
color='#006666'><b>This a teal bold 12-pt.' Verdana font with alignment set
to right.</b></font></p><br><li>This is bulleted text.</li><li><font
face='arial' size='12' color='#0000ff'><u> <a href='http://
www.adobe.com'>This is a bulleted link with underline and blue color set.</
a></u></font></li>";
]]></mx:Script>
<!-- The RichTextEditor control. To reference a subcontrol prefix its ID
with the RichTextEditor control ID. -->
<mx:RichTextEditor id="rte1"
backgroundColor="#ccffcc"
width="605"
headerColors="[#88bb88, #bbeebb]"
footerColors="[#bbeebb, #88bb88]"
title="Rich Text Editor"
htmlText="{htmlData}"
initialize="rte1.textArea.setStyle('backgroundColor', '0xeeffee')"
/>
</mx:Application>
Sizing the RichTextEditor control
The RichTextEditor control has the following default sizing properties:
Property
Default value
Default size
325 pixels wide by 300 pixels high
Minimum size
220 pixels wide by 200 pixels high
Maximum size
10000 by 10000 pixels
RichTextEditor control
401
The control does not resize in response to the size of the text in the TextArea control. If the
text exceeds the viewable space, by default, the TextArea control adds scroll bars. If you specify
a value for either the height or width property but not both, the control uses the default
value for the property that you do not set.
If you set a width value that results in a width less than 605 pixels wide, The RichTextEditor
control stacks the subcontrols in rows.
Programming RichTextEditor subcontrols
Your application can control the settings of any of the RichTextEditor subcontrols, such as the
TextArea, the ColorPicker, or any of the ComboBox or Button controls that control text
formatting. To refer to a RichTextEditor subcontrol, prefix the requested control’s ID, as
listed in the RichTextEditor entry in Adobe Flex 2 Language Reference, with the
RichTextEditor control ID. For example, to refer to the ColorPicker control in a
RichTextEditor control that has the ID rte1, use rte1.colorPicker.
Inheritable styles that you apply directly to a RichTextEditor control affect the underlying
Panel control and the subcontrols. Properties that you apply directly to a RichTextEditor
control affect the underlying Panel control only.
402
Using Text Controls
Setting RichTextEditor subcontrol properties and styles
The following simple code example shows how you can set and change the properties and
styles of the RichTextEditor control and its subcontrols. This example uses styles that the
RichTextEditor control inherits from the Panel class to set the colors of the Panel control
header and the tool bar container, and sets the TextArea control’s background color in the
RichTextEditor control’s creationComplete event member. When users click the buttons,
their click event listeners change the TextArea control’s background color and the selected
color of the ColorPicker control.
<?xml version="1.0"?>
<!-- textcontrols/RTESubcontrol.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
height="420">
<!-- The RichTextEditor control. To set the a subcontrol's style or
property, fully qualify the control ID. The footerColors style sets the
ControlBar colors. -->
<mx:RichTextEditor id="rte1"
backgroundColor="#ccffcc"
headerColors="[#88bb88, #bbeebb]"
footerColors="[#bbeebb, #88bb88]"
title="Rich Text Editor"
creationComplete="rte1.textArea.setStyle('backgroundColor','0xeeffee')"
text="Simple sample text"
/>
<!-- Button to set a white TextArea background. -->
<mx:Button
label="Change appearance"
click="rte1.textArea.setStyle('backgroundColor',
'0xffffff');rte1.colorPicker.selectedIndex=27;"
/>
<!-- Button to reset the display to its original appearance. -->
<mx:Button
label="Reset Appearance"
click="rte1.textArea.setStyle('backgroundColor',
'0xeeffee');rte1.colorPicker.selectedIndex=0;"
/>
</mx:Application>
Removing and adding RichTextEditor subcontrols.
You can remove any of the standard RichTextEditor subcontrols, such as the alignment
buttons. You can also add your own subcontrols, such as a button that pops up a find-andreplace dialog box.
RichTextEditor control
403
To remove an existing subcontrol
1.
Create a function that calls the removeChildAt method of the editor’s tool bar Container
subcontrol, specifying the control to remove.
2.
Call the method in the RichTextEditor control’s initialize event listener.
The following example removes the alignment buttons from a RichTextEditor control, and
shows the default appearance of a second RichTextEditor control:
<?xml version="1.0"?>
<!-- textcontrols/RTERemoveAlignButtons.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
public function removeAlignButtons():void {
rt1.toolbar.removeChild(rt1.alignButtons);
}
]]></mx:Script>
<mx:RichTextEditor id="rt1" title="RichTextEditor With No Align Buttons"
creationComplete="removeAlignButtons()"/>
<mx:RichTextEditor id="rt2" title="Default RichTextEditor"/>
</mx:Application>
To add a new subcontrol:
1.
Create an ActionScript function that defines the subcontrol. Also create any necessary
methods to support the control’s function.
2.
Call the method in the RichTextEditor control’s initialize event listener, as in the
following tag:
<mx:RichTextEditor id="rt" initialize="addMyControl()"
404
Using Text Controls
The following example adds a find-and-replace dialog box to a RichTextEditor control. It
consists of two files: the application, and a custom TitleWindow control that defines the findand-replace dialog (which also performs the find-and-replace operation on the text). The
application includes a function that adds a button to pop up the TitleWindow, as follows:
<?xml version="1.0"?>
<!-- textcontrols/CustomRTE.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
width="600" height="100%">
<mx:Script>
<![CDATA[
import mx.controls.*;
import mx.containers.*;
import flash.events.*;
import mx.managers.PopUpManager;
import mx.core.IFlexDisplayObject;
// The variable for the pop-up dialog box.
public var w:IFlexDisplayObject;
// Add the Find/Replace button to the Rich Text Editor control's
// tool bar container.
public function addFindReplaceButton():void {
var but:Button = new Button();
but.label = "Find/Replace";
but.addEventListener("click",findReplaceDialog);
rt.toolbar.addChild(but);
}
// The event listener for the Find/Replace button's click event
// creates a pop-up with a MyTitleWindow custom control.
public function findReplaceDialog(event:Event):void {
var w:MyTitleWindow = MyTitleWindow(PopUpManager.createPopUp
(this, MyTitleWindow, true));
w.height=200;
w.width=340;
// Pass the a reference to the textArea subcontrol
// so that the custom control can replace the text.
w.RTETextArea = rt.textArea;
PopUpManager.centerPopUp(w);
}
]]>
</mx:Script>
<mx:RichTextEditor id="rt" width="95%" title="RichTextEditor"
text="This is a short text."
initialize="addFindReplaceButton()"/>
</mx:Application>
RichTextEditor control
405
The following MyTitleWindow.mxml file defines the custom myTitleWindow control that
contains the find-and-replace interface and logic:
<?xml version="1.0"?>
<!-- A TitleWindow that displays the X close button. Clicking the close
button only generates a CloseEvent event, so it must handle the event to
close the control. -->
<mx:TitleWindow xmlns:mx="http://www.adobe.com/2006/mxml" title="Find/
Replace" showCloseButton="true" close="closeDialog();">
<mx:Script>
<![CDATA[
import mx.controls.TextArea;
import mx.managers.PopUpManager;
// Reference to the RichTextArea textArea subcontrol.
// It is set by the application findReplaceDialog method
// and used in the replaceAndClose method, below.
public var RTETextArea:TextArea;
// The event handler for the Replace button's click event.
// Replace the text in the RichTextEditor TextArea and
// close the dialog box.
public function replaceAndClose():void{
RTETextArea.text = RTETextArea.text.replace(ti1.text, ti2.text);
PopUpManager.removePopUp(this);
}
// The event handler for the TitleWindow close button.
public function closeDialog():void {
PopUpManager.removePopUp(this);
}
]]>
</mx:Script>
<!-- The TitleWindow subcontrols: the find and replace inputs,
their labels, and a button to initiate the operation. -->
<mx:Label text="Find what:"/>
<mx:TextInput id="ti1"/>
<mx:Label text="Replace with:"/>
<mx:TextInput id="ti2"/>
<mx:Button label="Replace" click="replaceAndClose();"/>
</mx:TitleWindow>
406
Using Text Controls
11
CHAPTER 11
Using Menu-Based Controls
Several Adobe Flex framework controls create or interact with menus. This topic describes
these controls and discusses how to use them.
Contents
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
About menu-based controls
Flex framework includes three controls that present hierarchical data in a cascading menu
format. All menu controls can have icons and labels for each menu item, and dispatch events
of the mx.events.MenuEvent class in response to user actions. You can use the following
menu-based controls:
Menu control A visual menu that can have cascading submenus. You typically display a
menu control in response to some user action, such as clicking a button. You cannot define a
Menu control by using an MXML tag; you must define it, display it, and hide it using
ActionScript.
MenuBar control
A horizontal bar of menu items. Each item in the menu bar can have a
submenu that displays when you click the MenuBar item. The MenuBar control is effectively
a static (non-pop-up) menu that displays the top level of the menu as the bar items.
PopUpMenuButton control A subclass of the PopUpButton control that displays a Menu
control when you click the secondary button. The primary button label changes when you
select an item from the pop-up menu.
407
Defining menu structure and data
All menu-based controls use data providers with the following characteristics to specify the
structure and contents of the menus:
■
The data providers are often hierarchical, but you can also have a single-level menu.
■
Individual menu items include fields that determine the menu item appearance and
behavior. Menu-based controls support fields that define the label text, an icon, the menu
item type, and item status. For information on meaningful fields, see “Specifying and
using menu entry information” on page 409.
About menu data providers
The dataProvider property of a menu-based control specifies an object that defines the
structure and contents of the menu. If a menu’s contents are dynamic, you change the menu
by modifying its data provider.
Menu-based controls typically get their data from hierarchical data providers, such as nested
arrays of objects or XML. If the menu represents dynamically changing data, you use an
object that implements the ICollectionView interface, such as ArrayCollection or
XMLListCollection.
Menu-based controls use a data descriptor to parse and manipulate the data provider
contents. By default, menu-based controls use a DefaultDataDescriptor class descriptor, but
you can create your own class and specify it in the Menu control’s dataDescriptor property.
The DefaultDataDescriptor class supports the following types of data:
XML
A string that contains valid XML text, or any of the following objects containing valid
E4X format XML data: an <mx:XML> or <mx:XMLList> compile-time tag, or an XML or
XMLList object.
Other objects
An array of items, or an object that contains an array of items, where a node’s
children are contained in an item named children. 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.
Collections
An object that implements the ICollectionView interface (such as the
ArrayCollection or XMLListCollection classes) and whose data source conforms to the
structure specified in either of the previous bullets. The DefaultDataDescriptor class includes
code to handle collections efficiently. Always use a collection as the data provider if the data in
the menu changes dynamically; otherwise, the Menu displays obsolete data.
408
Using Menu-Based Controls
For more information on hierarchical objects and data descriptors, including a detailed
description of the formats supported by the DefaultDataDescriptor, see “Data descriptors and
hierarchical data provider structure” on page 197.
As with all data-driven controls, if the data provider contents can change dynamically, and
you want the Menu to update with the changes, ensure that the data source is a collection,
such as an ArrayCollection or XMLListCollection object. To modify the menu, change the
underlying collection, and the menu will update its appearance accordingly.
Node (menu item) tags in the XML data can have any name. Many examples in this topic use
tags such as <node> for all menu items, or <menuItem> for top-level items and
<subMenuItem> for submenu items, but it might be more realistic to use tag names that
identify the data, such as <person>, <address>, and so on. The menu-handling code reads
through the XML and builds the display hierarchy based on the nested relationship of the
nodes. For more information, see “Specifying and using menu entry information”.
Most menus have multiple items at the top level, not a single root item. XML objects, such as
the XML object created by the <mx:XML> tag, must have a single root node. To display a menu
that uses a data provider that has a root that you do not want to display, set the Menu,
PopUpMenuButton, or MenuBar showRoot property to false.
Specifying and using menu entry information
Information in menu-based control data providers determines how each menu entry appears
and is used. To access or change the menu contents, you modify the contents of the data
provider.
The menu-based classes use the methods of the IMenuDataDescriptor class to access and
manipulate information in the data provider that defines the menu behavior and contents.
Flex provides a DefaultDataDescriptor class that implements these interface. The menu-based
controls use the DefaultDataDescriptor class if you do not set the dataDescriptor property.
This section describes the menu information you can provide, and the data provider fields and
values you use when using DefaultDataDescriptor class.
Menu entry types
Each data provider entry can specify an item type and type-specific information about the
menu item. Menu-based classes support the following item types (type field values):
normal
(the default) Selecting an item with the normal type triggers a change event, or, if
the item has children, opens a submenu.
Defining menu structure and data
409
check
Selecting an item with the check type toggles the menu item’s toggled property
between true and false values. When the menu item is in the true state, it displays a check
mark in the menu next to the item’s label.
radio Items with the radio type operate in groups, much like RadioButton controls; you
can select only one radio menu item in each group at a time. The example in this section
defines three submenu items as radio buttons within the group “one”.
When a radio button is selected, the radio item’s toggled property is set to true, and the
toggled properties of all other radio items in the group are set to false. The Menu control
displays a solid circle next to the radio button that is currently selected. The selection
property of the radio group is set to the label of the selected menu item.
separator
Items with the separator type provide a simple horizontal line that divides the
items in a menu into different visual groups.
Menu attributes
Menu items can specify several attributes that determine how the item is displayed and
behaves. The following table lists the attributes you can specify, their data types, their
purposes, and how the data provider must represent them if the menu uses the
DefaultDataDescriptor class to parse the data provider:
Attribute
Type
enabled
Boolean Specifies whether the user can select the menu item (true), or not
(false). If not specified, Flex treats the item as if the value were true.
If you use the default data descriptor, data providers must use an
enabled XML attribute or object field to specify this characteristic.
groupName
String
(Required, and meaningful, for radio type only) The identifier that
associates radio button items in a radio group. If you use the default
data descriptor, data providers must use a groupName XML attribute or
object field to specify this characteristic.
icon
Class
Specifies the class identifier of an image asset. This item is not used
for the check, radio, or separator types. You can use the checkIcon
and radioIcon styles to specify the icons used for radio and check
box items that are selected.
The menu’s iconField or iconFunction property determines the name
of the field in the data that specifies the icon, or a function for
determining the icons.
410
Description
Using Menu-Based Controls
Attribute
Type
Description
label
String
Specifies the text that appears in the control. This item is used for all
menu item types except separator.
The menu’s labelField or labelFunction property determines the
name of the field in the data that specifies the label, or a function for
determining the labels. (If the data provider is in E4X XML format,
you must specify one of these properties to display a label.) If the
data provider is an array of strings, Flex uses the string value as the
label.
toggled
Boolean Specifies whether a check or radio item is selected. If not specified,
Flex treats the item as if the value were false and the item is not
selected.
If you use the default data descriptor, data providers must use a
toggled XML attribute or object field to specify this characteristic.
type
String
Specifies the type of menu item. Meaningful values are separator,
check, or radio. Flex treats all other values, or nodes with no type
entry, as normal menu entries.
If you use the default data descriptor, data providers must use a type
XML attribute or object field to specify this characteristic.
Menu-based controls ignore all other object fields or XML attributes, so you can use them for
application-specific data.
Defining menu structure and data
411
Example: An Array menu data provider
The following example displays a Menu that uses an Array data provider and shows how you
define the menu characteristics in the data provider. For an application that specifies an
identical menu structure in XML, see “Example: Creating a simple Menu control”
on page 429.
<?xml version="1.0"?>
<!-- menus/ArrayDataProvider.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute">
<mx:Script>
<![CDATA[
import mx.controls.Menu;
// Method to create an Array-based menu.
private function createAndShow():void {
// The third parameter sets the showRoot property to false.
// You must set this property in the createMenu method,
// not later.
var myMenu:Menu = Menu.createMenu(null, menuData, true);
myMenu.show(10, 10);
}
// The Array data provider
[Bindable]
public var menuData:Array = [
{label: "MenuItem A", children: [
{label: "SubMenuItem A-1", enabled: false},
{label: "SubMenuItem A-2", type: "normal"}
]},
{label: "MenuItem B", type: "check", toggled: true},
{label: "MenuItem C", type: "check", toggled: false},
{type: "separator"},
{label: "MenuItem D", children: [
{label: "SubMenuItem D-1", type: "radio",
groupName: "g1"},
{label: "SubMenuItem D-2", type: "radio",
groupName: "g1", toggled: true},
{label: "SubMenuItem D-3", type: "radio",
groupName: "g1"}
]}
];
]]>
</mx:Script>
<!-- Button control to create and open the menu. -->
<mx:Button x="300" y="10"
label="Open Menu"
412
Using Menu-Based Controls
click="createAndShow();"/>
</mx:Application>
The following image shows the resulting control, with MenuItem D open; notice that check
item B and radio item D-2 are selected:
Example: An XML menu data provider with icons
The following example displays a menu control that uses XML as the data provider, and
specifies custom icons for the items in the control:
Defining menu structure and data
413
<?xml version="1.0"?>
<!-- menus/SimpleMenuControl.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
<mx:Script>
<![CDATA[
// Import the Menu control.
import mx.controls.Menu;
[Bindable]
[Embed(source="assets/topIcon.jpg")]
public var myTopIcon:Class;
[Bindable]
[Embed(source="assets/radioIcon.jpg")]
public var myRadioIcon:Class;
[Bindable]
[Embed(source="assets/checkIcon.gif")]
public var myCheckIcon:Class;
// Create and display the Menu control.
private function createAndShow():void {
var myMenu:Menu = Menu.createMenu(null, myMenuData, false);
myMenu.labelField="@label";
// Specify the check icon.
myMenu.setStyle('checkIcon', myCheckIcon);
// Specify the radio button icon.
myMenu.setStyle('radioIcon', myRadioIcon);
// Specify the icon for the topmenu items.
myMenu.iconField="@icon";
myMenu.show(10, 10);
}
]]>
</mx:Script>
<!-- Define the menu data. -->
<mx:XML format="e4x" id="myMenuData">
<root>
<menuitem label="MenuItem A" icon="myTopIcon">
<menuitem label="SubMenuItem A-1" enabled="False"/>
<menuitem label="SubMenuItem A-2"/>
</menuitem>
<menuitem label="MenuItem B" type="check" toggled="true"/>
<menuitem label="MenuItem C" type="check" toggled="false"
icon="myTopIcon"/>
414
Using Menu-Based Controls
<menuitem type="separator"/>
<menuitem label="MenuItem D" icon="myTopIcon">
<menuitem label="SubMenuItem D-1" type="radio"
groupName="one"/>
<menuitem label="SubMenuItem D-2" type="radio"
groupName="one" toggled="true"/>
<menuitem label="SubMenuItem D-3" type="radio"
groupName="one"/>
</menuitem>
</root>
</mx:XML>
<mx:VBox>
<!-- Define a Button control to open the menu -->
<mx:Button id="myButton"
label="Open Menu"
click="createAndShow();"/>
</mx:VBox>
</mx:Application>
Handling menu-based control events
User interaction with a Menu or menu-based control is event-driven; that is, applications
typically handle events generated when the user opens, closes, or selects within a menu, or
submenu or rolls over or out of menu items. For detailed information on events and how to
use them, see Chapter 5, “Using Events,” on page 83.
The Menu and MenuBar controls dispatch an identical set of menu-specific events. Event
handling with PopUpMenuButton controls differs from the other two controls, but shares
many elements in common with the others.
Handling Menu control events
The Menu control defines the following menu-specific event types, of the MenuEvent class:
change (MenuEvent.CHANGE) Dispatched when a user changes current menu selection
by using the keyboard or mouse.
itemClick
(MenuEvent.ITEM_CLICK) Dispatched when a user selects an enabled menu
item of type normal, check, or radio. This event is not dispatched when a user selects a
menu item of type separator, a menu item that opens a submenu, or a disabled menu item.
itemRollOut
(MenuEvent.ITEM_ROLL_OUT) Dispatched when the mouse pointer rolls
off of a Menu item.
Handling menu-based control events
415
itemRollOver
(MenuEvent.ITEM_ROLL_OVER) Dispatched when the mouse pointer
rolls onto a Menu item.
menuHide
(MenuEvent.MENU_HIDE) Dispatched when the entire menu or a submenu
closes.
menuShow
(MenuEvent.MENU_SHOW) Dispatched when the entire menu or a
submenu opens.
The event object passed to the event listener is of type MenuEvent and contains one or more
of the following menu-specific properties:
Property
Description
item
The item in the data provider for the menu item associated with the event.
index
The index of the item in the menu or submenu that contains it.
label
The label of the item.
menu
A reference to the Menu control where the event occurred.
menuBar
The MenuBar control instance that is the parent of the menu, or undefined
when the menu does not belong to a MenuBar. For more information, see
“MenuBar control” on page 431.
To access properties and fields of an object-based menu item, you specify the menu item field
name, as follows:
ta1.text = event.item.label
To access attributes of an E4X XML-based menu item, you specify the menu item attribute
name in E4X syntax, as follows:
ta1.text = [email protected]
NO T E
416
If you set an event listener on a submenu of a menu-based control, and the menu data
provider’s structure changes (for example, an element is removed), the event listener
might no longer exist. To ensure that the event listener is available when the data
provider structure changes, either listen on events of the menu-based control, not a
submenu, or add the event listener each time an event occurs that changes the data
provider’s structure.
Using Menu-Based Controls
The following example shows a menu with a simple event listener. For a more complex
example, see “Example: Using Menu control events” on page 422.
<?xml version="1.0"?>
<!-- menus/EventListener.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute">
<mx:Script>
<![CDATA[
import mx.controls.Menu;
import mx.events.MenuEvent;
// Function to create and show a menu.
private function createAndShow():void {
var myMenu:Menu = Menu.createMenu(null, myMenuData, false);
myMenu.labelField="@label"
// Add an event listener for the itemClick event.
myMenu.addEventListener(MenuEvent.ITEM_CLICK,
itemClickInfo);
// Show the menu.
myMenu.show(225, 10);
}
// The event listener for the itemClick event.
private function itemClickInfo(event:MenuEvent):void {
ta1.text="event.type: " + event.type;
ta1.text+="\nevent.index: " + event.index;
ta1.text+="\nItem label: " + [email protected]
ta1.text+="\nItem selected: " + [email protected];
ta1.text+= "\nItem type: " + [email protected];
}
]]>
</mx:Script>
<!-- The XML-based menu data provider. -->
<mx:XML id="myMenuData">
<xmlRoot>
<menuitem label="MenuItem A" >
<menuitem label="SubMenuItem A-1" enabled="false"/>
<menuitem label="SubMenuItem A-2"/>
</menuitem>
<menuitem label="MenuItem B" type="check" toggled="true"/>
<menuitem label="MenuItem C" type="check" toggled="false"/>
<menuitem type="separator"/>
<menuitem label="MenuItem D" >
<menuitem label="SubMenuItem D-1" type="radio"
groupName="one"/>
<menuitem label="SubMenuItem D-2" type="radio"
groupName="one" toggled="true"/>
Handling menu-based control events
417
<menuitem label="SubMenuItem D-3" type="radio"
groupName="one"/>
</menuitem>
</xmlRoot>
</mx:XML>
<!-- Button controls to open the menus. -->
<mx:Button x="10" y="5"
label="Open Menu"
click="createAndShow();"/>
<!-- Text area to display the event information -->
<mx:TextArea x="10" y="40"
width="200" height="100"
id="ta1"/>
</mx:Application>
Handling MenuBar events
The following figure shows a MenuBar control:
Menu bar
Pop-up submenu
For the menu bar, the following events occur:
change
(MenuEvent.CHANGE) Dispatched when a user changes current menu bar
selection by using the keyboard or mouse. This event is also dispatched when the user changes
the current menu selection in a pop-up submenu. When the event occurs on the menu bar,
the menu property of the MenuEvent object is null.
itemRollOut
(MenuEvent.ITEM_ROLL_OUT) Dispatched when the mouse pointer rolls
off of a menu bar item.
itemRollOver
(MenuEvent.ITEM_ROLL_OVER) Dispatched when the mouse pointer
rolls onto a menu bar item.
menuHide
418
(MenuEvent.MENU_HIDE) Dispatched when a pop-up submenu closes.
Using Menu-Based Controls
menuShow (MenuEvent.MENU_SHOW) Dispatched when a pop-up submenu opens, or
the user selects a menu bar item with no drop-down menu.
NO T E
The MenuBar control does not dispatch the itemClick event when you select an item on
the menu bar; it only dispatches the itemClick event when you select an item on a popup submenu.
For each pop-up submenu, the MenuBar dispatches the change, itemClick, itemRollOut,
itemRollOver, menuShow, and menuHide events in the same way it does for the Menu
control. Handle events triggered by the pop-up menus as you would handle events from
Menu controls. For more information, see “Handling Menu control events” on page 415.
Handling menu-based control events
419
The following example handles events for the menu bar and for the pop-up submenus:
<?xml version="1.0"?>
<!-- menus/MenuBarEventInfo.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="initCollections();">
<mx:Script>
<![CDATA[
import mx.events.MenuEvent;
import mx.controls.Alert;
import mx.collections.*;
[Bindable]
public var menuBarCollection:XMLListCollection;
private var menubarXML:XMLList =<>
<menuitem label="Menu1">
<menuitem label="MenuItem 1-A" data="1A"/>
<menuitem label="MenuItem 1-B" data="1B"/>
</menuitem>
<menuitem label="Menu2">
<menuitem label="MenuItem 2-A" data="2A"/>
<menuitem label="MenuItem 2-B" data="2B"/>
</menuitem>
<menuitem label="Menu3" data="M3"/>
</>
// Event handler to initialize the MenuBar control.
private function initCollections():void {
menuBarCollection = new XMLListCollection(menubarXML);
}
// Event handler for the MenuBar control's change event.
private function changeHandler(event:MenuEvent):void {
// Only open the Alert for a selection in a pop-up submenu.
// The MenuEvent.menu property is null for a change event
// dispatched by the menu bar.
if (event.menu != null) {
Alert.show("Label: " + [email protected] + "\n" +
"Data: " + [email protected], "Clicked menu item");
}
}
// Event handler for the MenuBar control's itemRollOver event.
private function rollOverHandler(event:MenuEvent):void {
rollOverTextArea.text = "type: " + event.type + "\n";
rollOverTextArea.text += "target menuBarIndex: " +
event.index + "\n";
}
420
Using Menu-Based Controls
// Event handler for the MenuBar control's itemClick event.
private function itemClickHandler(event:MenuEvent):void {
itemClickTextArea.text = "type: " + event.type + "\n";
itemClickTextArea.text += "target menuBarIndex: " +
event.index + "\n";
}
]]>
</mx:Script>
<mx:Panel title="MenuBar Control Example"
height="75%" width="75%"
paddingTop="10" paddingLeft="10">
<mx:Label
width="100%"
color="blue"
text="Select a menu item."/>
<mx:MenuBar labelField="@label"
dataProvider="{menuBarCollection}"
change="changeHandler(event);"
itemClick="itemClickHandler(event);"
itemRollOver="rollOverHandler(event);"/>
<mx:TextArea id="rollOverTextArea"
width="200" height="100"/>
<mx:TextArea id="itemClickTextArea"
width="200" height="100"/>
</mx:Panel>
</mx:Application>
Handling menu-based control events
421
Example: Using Menu control events
The following example lets you experiment with Menu control events. It lets you display two
menus, one with an XML data provider and one with an Array data provider. A TextArea
control displays information about each event as a user opens the menus, moves the mouse,
and selects menu items. It shows some of the differences in how you handle XML and objectbased menus, and indicates some of the types of information that are available about each
Menu event.
<?xml version="1.0"?>
<!-- menus/ExtendedMenuExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute">
<mx:Script>
<![CDATA[
// Import the Menu control and MenuEvent class.
import mx.controls.Menu;
import mx.events.MenuEvent;
//Define a variable for the Menu control.
private var myMenu:Menu;
// The event listener that creates menu with an XML data
// provider and adds event listeners for the menu.
private function createAndShow():void {
// Clear the event output display.
ta1.text="";
// Don't show the (single) XML root node in the menu.
myMenu = Menu.createMenu(null, myMenuData, false);
//You must set the labelField explicitly for XML data providers.
myMenu.labelField="@label"
myMenu.addEventListener(MenuEvent.ITEM_CLICK, menuShowInfo);
myMenu.addEventListener(MenuEvent.MENU_SHOW, menuShowInfo);
myMenu.addEventListener(MenuEvent.MENU_HIDE, menuShowInfo);
myMenu.addEventListener(MenuEvent.ITEM_ROLL_OUT, menuShowInfo);
myMenu.addEventListener(MenuEvent.ITEM_ROLL_OVER,
menuShowInfo);
myMenu.show(225, 10);
}
// The event listener for the menu events.
// Retain information on all events for a menu instance.
private function menuShowInfo(event:MenuEvent):void {
ta1.text="event.type: " + event.type;
ta1.text+="\nevent.label: " + event.label;
// The index value is -1 for menuShow and menuHide events.
ta1.text+="\nevent.index: " + event.index;
//The item field is null for show and hide events.
422
Using Menu-Based Controls
if (event.item) {
ta1.text+="\nItem label: " + [email protected]
ta1.text+="\nItem selected: " + [email protected];
ta1.text+= "\nItem type: " + [email protected];
}
}
// The event listener that creates an object-based menu
// and adds event listeners for the menu.
private function createAndShow2():void {
// Show the top (root) level objects in the menu.
myMenu = Menu.createMenu(null, menuData, true);
myMenu.addEventListener(MenuEvent.ITEM_CLICK, menuShowInfo2);
myMenu.addEventListener(MenuEvent.MENU_SHOW, menuShowInfo2);
// The following line is commented to so you can see the
// results of an ITEM_CLICK event.
// (The menu hides immediately after the click.)
// myMenu.addEventListener(MenuEvent.MENU_HIDE, menuShowInfo2);
myMenu.addEventListener(MenuEvent.ITEM_ROLL_OVER,
menuShowInfo2);
myMenu.addEventListener(MenuEvent.ITEM_ROLL_OUT,
menuShowInfo2);
myMenu.show(225, 10);
}
// The event listener for the object-based Menu events.
private function menuShowInfo2(event:MenuEvent):void {
ta1.text="event.type: " + event.type;
ta1.text+="\nevent.label: " + event.label;
// The index value is -1 for menuShow and menuHide events.
ta1.text+="\nevent.index: " + event.index;
// The item field is null for show and hide events.
if (event.item) {
ta1.text+="\nItem label: " + event.item.label
ta1.text+="\nItem selected: " + event.item.toggled;
ta1.text+= "\ntype: " + event.item.type;
}
}
// The object-based data provider, an Array of objects.
// Its contents is identical to that of the XML data provider.
[Bindable]
public var menuData:Array = [
{label: "MenuItem A", children: [
{label: "SubMenuItem A-1", enabled: false},
{label: "SubMenuItem A-2", type: "normal"}
]},
{label: "MenuItem B", type: "check", toggled: true},
{label: "MenuItem C", type: "check", toggled: false},
{type: "separator"},
Handling menu-based control events
423
{label: "MenuItem D", children: [
{label: "SubMenuItem D-1", type: "radio", groupName: "g1"},
{label: "SubMenuItem D-2", type: "radio", groupName: "g1",
toggled: true},
{label: "SubMenuItem D-3", type: "radio", groupName: "g1"}
]}
];
]]>
</mx:Script>
<!-- The XML-based menu data provider.
The <mx:XML tag requires a single root. -->
<mx:XML id="myMenuData">
<xmlRoot>
<menuitem label="MenuItem A" >
<menuitem label="SubMenuItem A-1" enabled="false"/>
<menuitem label="SubMenuItem A-2"/>
</menuitem>
<menuitem label="MenuItem B" type="check" toggled="true"/>
<menuitem label="MenuItem C" type="check" toggled="false"/>
<menuitem type="separator"/>
<menuitem label="MenuItem D" >
<menuitem label="SubMenuItem D-1" type="radio"
groupName="one"/>
<menuitem label="SubMenuItem D-2" type="radio"
groupName="one" toggled="true"/>
<menuitem label="SubMenuItem D-3" type="radio"
groupName="one"/>
</menuitem>
</xmlRoot>
</mx:XML>
<!-- Button controls to open the menus. -->
<mx:Button x="10" y="5"
label="Open XML Popup"
click="createAndShow();"/>
<mx:Button x="10" y="35"
label="Open Object Popup"
click="createAndShow2();"/>
<!-- Text area to display the event information -->
<mx:TextArea x="10" y="70"
width="200" height="300"
id="ta1"/>
</mx:Application>
424
Using Menu-Based Controls
Handling PopUpMenuButton control events
Because the PopUpMenuButton is a subclass of the PopUpButton control, it supports all of
that control’s events. When the uer clisks the main button, the PopUpMenuButton control
dispatches a click (MouseEvent.CLICK) event.
When the user clicks the PopUpMenuButton main button, the control dispatches an
itemClick (MenuEvent.ITEM_CLICK) event that contains information about the selected
menu item. Therefore, the same itemClick event is dispatched when the user clicks the main
button or selects the current item from the pop-up menu. Because the same event is
dispatched in both cases, clicking on the main button produces the same behavior as clicking
on the last selected menuItem, so the main button plays the role of a frequently used menu
item.
The following example shows how the PopUpMenuButton generates events and how an
application can handle them.
When the user selects an item from the pop-up menu, the following things occur:
■
The PopUpMenuButton dispatches an itemClick event.
■
The application’s itemClickHandler() event listener function handles the itemClick
event and displays the information about the event in an Alert control.
When the user clicks the main button, the following things occur:
■
The PopUpMenuButton control dispatches a click event.
■
The PopUpMenuButton control dispatches an itemClick event.
■
The application’s itemClickHandler() event listener function handles the itemClick
event and displays information about the selected Menu item in an Alert control.
Handling menu-based control events
425
■
The application’s clickHandler() event listener function also handles the
MouseEvent.CLICK event, and displays the Button label in an Alert control.
<?xml version="1.0"?>
<!-- menus/PopUpMenuButtonEvents.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
height="600" width="600"
creationComplete="initData();">
<mx:Script>
<![CDATA[
import mx.events.*;
import mx.controls.*;
// Set the Inbox (fourth) item in the menu as the button item.
private function initData():void {
Menu(p1.popUp).selectedIndex=3;
}
// itemClick event handler, invoked when you select from the menu.
// Shows the event's label, index properties, and the values of the
// label and data fields of the data provider entry specified by
// the event's item property.
public function itemClickHandler(event:MenuEvent):void {
Alert.show("itemClick event label: " + event.label
+ " \nindex: " + event.index
+ " \nitem.label: " + event.item.label
+ " \nitem.data: " + event.item.data);
}
//Click event handler for the main button.
public function clickHandler(event:MouseEvent):void {
Alert.show(" Click Event currentTarget.label: "
+ event.currentTarget.label);
}
//The menu data provider
[Bindable]
public var menuDP:Array = [
{label: "Inbox", data: "inbox"},
{label: "Calendar", data: "calendar"},
{label: "Sent", data: "sent"},
{label: "Deleted Items", data: "deleted"},
{label: "Spam", data: "spam"}
];
]]></mx:Script>
<mx:PopUpMenuButton id="p1"
showRoot="true"
dataProvider="{menuDP}"
426
Using Menu-Based Controls
click="clickHandler(event)"
itemClick="itemClickHandler(event);"
/>
</mx:Application>
Menu control
The Menu control is a pop-up control that contains a menu of individually selectable choices.
You use ActionScript to create a Menu control that pops up in response to a user action,
typically as part of an event listener. Because you create a Menu control in response to an
event, it does not have an MXML tag; you can create Menu controls in ActionScript only.
For complete reference information, see Menu in Adobe Flex 2 Language Reference.
About the Menu Control
The following example shows a Menu control:
In this example, the MenuItem A and MenuItem D items open submenus. Submenus open
when the user moves the mouse pointer over the parent item or accesses the parent item by
using keyboard keys.
The default location of the Menu control is the upper-left corner of your application, at x, y
coordinates 0,0. You can pass x and y arguments to the show() method to control the
position relative to the application.
After a Menu opens, it remains visible until the user selects an enabled menu item, the user
selects another component in the application, or a script closes the menu.
To create a static menu that stays visible all the time, use the MenuBar control or
PopUpMenuButton control. For more information on the MenuBar control, see “MenuBar
control” on page 431. For more information on the PopUpMenuButton control, see
“PopUpMenuButton control” on page 433.
Menu control
427
The Menu control has the following sizing characteristics:
Property
Default value
Default size
The width is determined from the Menu text. The default height is the
number of menu rows multiplied by 19 pixels per row (the default row
height).
Creating a Menu control
You cannot create a Menu control by using an MXML tag; you must create it in ActionScript.
To create a Menu control:
1.
Create an instance of the Menu control by calling the static ActionScript
Menu.createMenu() method and passing the method an instance of the data provider that
contains the information that populates the control as the second parameter; for example:
var myMenu:Menu = Menu.createMenu(null, myMenuData);
(The first parameter can optionally specify the parent container of the menu.)
If you do not display the root node of the data provider, for example, if the data provider
is an XML document in E4X format, use a third parameter with the value false. This
parameter sets the menu’s showRoot property. The following example creates a menu that
does not show the data provider root:
var myMenu:Menu = Menu.createMenu(null, myMenuData, false);
N OT E
2.
To hide the root node, you must set the showRoot property in the createMenu method.
Setting the property after you create the menu has no effect.
Display the Menu instance by calling the ActionScript Menu.show() method; for example:
myMenu.show(10, 10);
N OT E
428
The show() method automatically adds the Menu object to the display list, and the hide()
method automatically removes it from the display list. Clicking outside the menu (or
pressing Escape) also hides the Menu object and removes it from the display list.
If you create a Menu object by using the Menu.createMenu() method, the Menu is
removed from the display list automatically when it is closed. To prevent this default
behavior, you can listen for the menuHide event and call preventDefault() on the event
object.
Menus displayed using the Menu.popUpMenu() method are not removed automatically; you
must call the PopUpManager.removePopUp() method on the Menu object.
Using Menu-Based Controls
Example: Creating a simple Menu control
The following example uses the <mx:XML> tag to define the data for the Menu control and a
Button control to trigger the event that opens the Menu control:
<?xml version="1.0"?>
<!-- menus/SimpleMenuControl.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
<mx:Script>
<![CDATA[
// Import the Menu control.
import mx.controls.Menu;
// Create and display the Menu control.
private function createAndShow():void {
var myMenu:Menu = Menu.createMenu(null, myMenuData, false);
myMenu.labelField="@label";
myMenu.show(10, 10);
}
]]>
</mx:Script>
<!-- Define the menu data. -->
<mx:XML format="e4x" id="myMenuData">
<root>
<menuitem label="MenuItem A" >
<menuitem label="SubMenuItem A-1" enabled="False"/>
<menuitem label="SubMenuItem A-2"/>
</menuitem>
<menuitem label="MenuItem B" type="check" toggled="true"/>
<menuitem label="MenuItem C" type="check" toggled="false"/>
<menuitem type="separator"/>
<menuitem label="MenuItem D" >
<menuitem label="SubMenuItem D-1" type="radio"
groupName="one"/>
<menuitem label="SubMenuItem D-2" type="radio"
groupName="one" toggled="true"/>
<menuitem label="SubMenuItem D-3" type="radio"
groupName="one"/>
</menuitem>
</root>
</mx:XML>
<mx:VBox>
<!-- Define a Button control to open the menu -->
<mx:Button id="myButton"
label="Open Menu"
click="createAndShow();"/>
</mx:VBox>
Menu control
429
</mx:Application>
You can assign any name to node tags in the XML data. In the previous sample, each node is
named with the generic <menuitem> tag, but you can have used <node>, <subNode>,
<person>, <address> and so on.
Because this example uses an E4X XML data source, you must specify the label field using the
E4X @ attribute specifier syntax, and you tell the control not to show the data provider root
node.
Several attributes or fields. such as the type attribute, have meaning to the Menu control. For
information on how Flex interprets and uses the data provider data, see “Specifying and using
menu entry information” on page 409.
Menu control user interaction
You can use the mouse or the keyboard to interact with a Menu control. Clicking selects a
menu item and closes the menu, except with the following types of menu items:
Disabled items or separators
Rolling over or clicking menu items has no effect and the
menu remains visible.
Submenu anchors
Rolling over the items activates the submenu; clicking them has no
effect; rolling onto any menu item other than one of the submenu items closes the submenu.
When a Menu control has focus, you can use the following keys to control it:
Key
Description
Down Arrow
Up Arrow
Moves the selection down and up the rows of the menu. The selection loops at
the top or bottom row.
Right Arrow
Opens a submenu, or moves the selection to the next menu in a menu bar.
Left Arrow
Closes a submenu and returns focus to the parent menu (if a parent menu
exists), or moves the selection to the previous menu in a menu bar (if the menu
bar exists).
Enter
Opens a submenu, has the effect of clicking and releasing the mouse on a row
if a submenu does not exist.
Escape
Closes a menu level.
430
Using Menu-Based Controls
MenuBar control
A MenuBar control displays the top level of a menu as a horizontal bar of menu items, where
each item on the bar can pop up a submenu. The MenuBar control interprets the data
provider in the same way as the Menu control, and supports the same events as the Menu
control. Unlike the Menu control, a MenuBar control is static; that is, it does not function as
a pop-up menu, but is always visible in your application. Because the MenuBar is static, you
can define it directly in MXML
For complete reference information, see MenuBar in Adobe Flex 2 Language Reference. For
more information on the Menu control, see “Handling Menu control events” on page 415.
About the MenuBar control
The following example shows a MenuBar control:
The control shows the labels of the top level of the data provider menu. When a user selects a
top-level menu item, the MenuBar control opens a submenu. The submenu stays open until
the user selects another top-level menu item, selects a submenu item, or clicks outside the
MenuBar area.
The MenuBar control has the following sizing characteristics:
Property
Default value
Default size
The width is determined from the menu text, with a minimum value of 27 pixels
for the width. The default value for the height is 22 pixels.
Creating a MenuBar control
You define a MenuBar control in MXML by using the <mx:MenuBar> tag. Specify an id value
if you intend to refer to a component elsewhere in your MXML application, either in another
tag or in an ActionScript block.
You specify the data for the MenuBar control by using the dataProvider property. The
MenuBar control uses the same types of data providers as does the Menu control. For more
information on data providers for Menu and MenuBar controls, see “Defining menu
structure and data” on page 408. For more information on hierarchical data providers, see
“Using hierarchical data providers” on page 197.
MenuBar control
431
In a simple case for creating a MenuBar control, you might use an <mx:XML> or
<mx:XMLList> tag and standard XML node syntax to define the menu data provider. When
you used an XML-based data provider, you must keep the following rules in mind:
■
With the <mx:XML> tag you must have a single root node, and you set the showRoot
property of the MenuBar control to false. (otherwise, your MenuBar would have only
the root as a button). With the <mx:XMLList> tag you define a list of XML nodes, and the
top level nodes define the bar buttons.
■
If your data provider has a label attribute (even if it is called “label”), you must set the
MenuBar control’s labelField property and use the E4X @ notation for the label; for
example:
labelField=”@label”
The dataProvider property is the default property of the MenuBar control, so you can define
the XML or XMLList object as a direct child of the <mx:MenuBar> tag, as the following
example shows:
<?xml version="1.0"?>
<!-- menus/MenuBarControl.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
<!-- Define the menu; dataProvider is the default MenuBar property.
Because this uses an XML data provider, specify the labelField and
showRoot properties. -->
<mx:MenuBar id="myMenuBar" labelField="@label">
<mx:XMLList>
<menuitem label="MenuItem A" >
<menuitem label="SubMenuItem A-1" enabled="False"/>
<menuitem label="SubMenuItem A-2"/>
</menuitem>
<menuitem label="MenuItem B" type="check" selected="true"/>
<menuitem label="MenuItem C" type="check" selected="false"/>
<menuitem label="MenuItem D" >
<menuitem label="SubMenuItem D-1" type="radio" groupName="one"/>
<menuitem label="SubMenuItem D-2" type="radio" groupName="one"
selected="true"/>
<menuitem label="SubMenuItem D-3" type="radio" groupName="one"/>
</menuitem>
</mx:XMLList>
</mx:MenuBar>
</mx:Application>
The top-level nodes in the MenuBar control correspond to the buttons on the bar. Therefore,
in this example, the MenuBar control displays the four labels shown in the preceding image.
432
Using Menu-Based Controls
You can assign any name to node tags in the XML data. In the previous example, each node is
named with the generic <menuitem> tag, but you can use <node>, <subNode>, <person>,
<address>, and so on. Several attributes or fields. such as the type attribute, have meaning to
the MenuBar control. For information on how Flex interprets and uses the data provider data,
see “Specifying and using menu entry information” on page 409.
MenuBar control user interaction
The user interaction of the MenuBar is the same as for the Menu control, with the following
difference: When the MenuBar control is has the focus, the left arrow opens the previous
menu. If the current menu bar item has a closed pop-up menu, the right arrow opens the
current menu; if the pop-up menu is open, the right arrow opens the next menu. (The
behavior wraps around the ends of the MenuBar control.)
For more information, see “Menu control user interaction” on page 430.
PopUpMenuButton control
The PopUpMenuButton is a PopUpButton control whose secondary button pops up a Menu
control. When the user selects an item from the pop-up menu, the main button of the
PopUpButton changes to show the icon and label of the selected menu item. Unlike the
Menu and MenuBar controls, the PopUpMenuButton supports only a single-level menu.
For complete reference information, see PopUpMenuButton in Adobe Flex 2 Language
Reference. For more information on the Menu control, see “Handling Menu control events”
on page 415. For more information on PopUpButton controls, see “PopUpButton control”
on page 273.
PopUpMenuButton control
433
About the PopUpMenuButton control
The following example shows a PopUpMenuButton control before and after clicking the
secondary pop-up button:
The PopUpMenuButton work as follows:
■
When you click the smaller button, which by default displays a v icon, the control displays
a pop-up menu below the button.
■
When you select an item from the pop-up menu, the main PopUpMenuButton button
label changes to show the selected item’s label and the PopUpMenuButton control
dispatches a MenuEvent.CHANGE event.
■
When you click the main button, the PopUpMenuButton control dispatches a
MenuEvent.CHANGE event and a MouseEvent.ITEM_CLICK event.
For information on handling PopUpMenuButton events, see “Handling PopUpMenuButton
control events” on page 425
The PopUpMenuButton control lets users change the function of the main button by
selecting items from the pop-up menu. The most recently selected item becomes the main
button item.
This behavior is useful for buttons when there are a number of user actions, users tend to
select the same option frequently, and the application developer cannot assume which option
should be the default. Text editors often use such controls in their control bar for options,
such as spacing, for which a user is likely to have a preferred setting, but the developer cannot
determine it in advance. Microsoft Word, for example, uses such controls for specifying line
spacing, borders, and text and highlight color.
You can use the PopUpButton control to create pop-up menu buttons with behaviors that
differ from those of the PopUpMenuButton; for example, buttons that do not change the
default action of the main button when the user selects a menu item. For more information,
see “PopUpButton control” on page 273.
434
Using Menu-Based Controls
The PopUpMenuButton control has the following sizing characteristics:
Property
Default value
Default size
Sufficient to accommodate the label and any icon on the main button, and
the icon on the pop-up button. The control does not reserve space for the
menu.
Minimum size
0
Maximum size
10000 by 10000
Creating a PopUpMenuButton control
You define a PopUpMenuButton control in MXML by using the <mx:PopUpMenuButton>
tag. Specify an id value if you intend to refer to a component elsewhere in your MXML
application, either in another tag or in an ActionScript block.
You specify the data for the PopUpMenuButton control by using the dataProvider property.
For information on valid data providers, including their structure and contents, see “Defining
menu structure and data” on page 408.
By default, the initially selected item is the first item in the pop-up menu dataProvider, and
the default main button label is the item’s label, as determined by the labelField or
labelFunction property. To set the initial main button label to a specific item’s label and
functionality, write a listener for the PopUpMenuButton control’s creationComplete event
that sets the selectedIndex property of the Menu subcontrol, as follows:
Menu(MyPopUpControl.popUp).selectedIndex=2;
You must cast the PopUpMenuButton control’s popUp property to a Menu because the
property type is IUIComponent, not Menu.
You can also use the label property of the PopUpMenuButton control to set the main button
label, as described in “Using the label property” on page 437.
When a popped up menu closes, it loses its selection and related properties.
NO T E
You must use the PopUpMenuButton’s creationComplete event, not the initialize
event to set the main button label from the data provider.
PopUpMenuButton control
435
Example: Creating a PopUpMenuButton control
The following example creates a PopUpMenuButton control using an E4X XML data
provider.
<?xml version="1.0"?>
<!-- menus/PopUpMenuButtonControl.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.controls.Menu
// The initData function sets the initial value of the button
// label by setting the Menu subcontrol's selectedIndex property.
// You must cast the popUp property to a Menu.
private function initData():void {
Menu(pb2.popUp).selectedIndex=2;
}
]]>
</mx:Script>
<mx:XML format="e4x" id="dp2">
<root>
<editItem label="Cut"/>
<editItem label="Copy"/>
<editItem label="Paste"/>
<separator type="separator"/>
<editItem label="Delete"/>
</root>
</mx:XML>
<mx:PopUpMenuButton id="pb2"
dataProvider="{dp2}"
labelField="@label"
showRoot="false"
creationComplete="initData();"/>
</mx:Application>
Because this example uses an E4X XML data source, you must specify the label field using the
E4X @ attribute specifier syntax, and you must tell the control not to show the data provider
root node.
436
Using Menu-Based Controls
Using the label property
The label property of the PopUpMenuButton control specifies the contents of the label on
the main button, and overrides any label from the pop-up menu that is determined by the
labelField or labelFunction property. The label property is useful for creating a main
button label with fixed and a variable parts; for example, a mail “Send to:” button where only
the destination text is controlled by the pop-up menu, so the main button could say “Send to:
Inbox” or “Send to: Trash” based on the selection from a menu that lists “Menu” and “Trash.”
To use a dynamic label property, use a PopUpMenuButton control change event listener to
set the label based on the event’s label property, as in the following example:
<?xml version="1.0"?>
<!-- menus/PopUpMenuButtonLabel.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
height="600" width="600">
<mx:Script>
<![CDATA[
import mx.events.MenuEvent;
public function itemClickHandler(event:MenuEvent):void {
event.currentTarget.label= "Send to: " + event.label;
}
[Bindable]
public var menuData:Array = [
{label: "Inbox", data: "inbox"},
{label: "Calendar", data: "calendar"},
{label: "Sent", data: "sent"},
{label: "Deleted Items", data: "deleted"},
{label: "Spam", data: "spam"}
];
]]>
</mx:Script>
<mx:PopUpMenuButton id="p1"
showRoot="true"
dataProvider="{menuData}"
label="Send to: Inbox"
itemClick="itemClickHandler(event);"/>
</mx:Application>
PopUpMenuButton control
437
PopUpMenuButton user interaction
The user interaction of the PopUpMenuButton control main button and secondary button is
the same as for the PopUpButton control. The user interaction with the pop-up menu is the
same as for the Menu control. For more information on the PopUpButton user interaction,
see “User interaction” on page 276. For more information on Menu control user interaction,
see “Menu control user interaction” on page 430.
438
Using Menu-Based Controls
12
CHAPTER 12
Using Data-Driven Controls
Several Adobe Flex controls take input from a data provider, an object that contains data. For
example, a Tree control reads data from a data provider to define the structure of the tree and
any associated data assigned to each tree node.
This topic describes several of the controls that use a data provider, focusing on controls that
let you visualize complex data. It includes examples of different ways to populate these
controls by using a data provider. The following topics also provide information on data
providers and controls that use data providers:
■
Chapter 7, “Using Data Providers and Collections,” on page 161 contains details on data
providers and how to use collections as data providers.
■
Chapter 11, “Using Menu-Based Controls,” on page 407 contains information on using
Menu, MenuBar, and PopUpMenuButton controls.
■
Chapter 16, “Using Navigator Containers,” on page 627 contains information on
navigator containers, such as TabNavigator and Accordion that use data providers to
populate their structures.
■
Chapter 53, “Introduction to Charts,” on page 1573 contains information on using chart
controls.
Contents
List control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
HorizontalList control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
TileList control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
ComboBox control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .458
DataGrid control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
Tree control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .479
439
List control
The List control displays a vertical list of items. Its functionality is very similar to that of the
SELECT form element in HTML. It often contains a vertical scroll bar that lets users access the
items in the list. An optional horizontal scroll bar lets users view items when the full width of
the list items is unlikely to fit. The user can select one or more items from the list.
NO T E
The HorizontalList, TileList, DataGrid, Menu, and Tree controls are derived from the
List control or its immediate parent, the ListBase class. As a result, much of the
information for the List control applies to these controls.
For complete reference information, see List in Adobe Flex 2 Language Reference.
The following image shows a List control:
List control sizing
The List control has the following default sizing properties:
Property
Default value
Default size
Wide enough to fit the widest label in the first seven visible items (or all
visible items in the list, if there are less than seven), and seven rows high,
where each row is 20 pixels high.
Minimum size
0
Maximum size
5000 by 5000
If you specify horizontalScrollPolicy="on", the default width of a List control does not
change; it is still large enough to display the widest visible label. If you set
horizontalScrollPolicy="on", and specify a List control pixel width, you can use the
measureWidthOfItems() method to ensure that the scroll bar rightmost position
corresponds to the right edge of the content, as the following example shows. Notice that the
additional 5 pixels ensures that the rightmost character of the text displays properly.
<mx:List width="200" id="li2" horizontalScrollPolicy="on"
maxHorizontalScrollPosition="{li2.measureWidthOfItems() - li2.width +
5}">
440
Using Data-Driven Controls
The preceding line ensures that the rightmost position of the scroll bar puts the end of the
longest measured list item near the right edge of the List control. Using this technique,
however, can reduce application efficiency, so you might consider using explicit sizes instead.
Lists, and all subclasses of the ListBase class determine their sizes when a style changes or the
data provider changes.
If you set a width property that is less than the width of the longest label and specify the
horizontalScrollPolicy="off", labels that exceed the control width are clipped.
Creating a List control
You use the <mx:List> tag to define a List control. 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 List control uses a list-based data provider. For more information, see “About data
providers” on page 162.
You specify the data for the List control by using the dataProvider property of the control.
However, because dataProvider is the List control’s default property, you do not have to
specify a <mx:dataProvider> child tag of the <mx:List> tag. In the simplest case for
creating a static List control, you need only put <mx:String> tags in the control body,
because Flex also automatically interprets the multiple tags as an Array of Strings, as the
following example shows:
<?xml version="1.0"?>
<!-- dpcontrols/ListDataProvider.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:List>
<mx:dataProvider>
<mx:String>AK</mx:String>
<mx:String>AL</mx:String>
<mx:String>AR</mx:String>
</mx:dataProvider>
</mx:List>
</mx:Application>
The index of items in the List control is zero-based, which means that values are 0, 1, 2, ... ,
n - 1, where n is the total number of items. The value of the item is its label text.
List control
441
You typically use events to handle user interaction with a List control. The following example
code adds a handler for a change event to the List control. Flex broadcasts a
mx.ListEvent.CHANGE event when the value of the control changes due to user interaction.
<?xml version="1.0"?>
<!-- dpcontrols/ListChangeEvent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import flash.events.Event;
public function changeEvt(event:Event):void {
forChange.text=event.currentTarget.selectedItem.label + " " +
event.currentTarget.selectedIndex;
}
]]>
</mx:Script>
<mx:List width="35" change="changeEvt(event)">
<mx:Object label="AL" data="Montgomery"/>
<mx:Object label="AK" data="Juneau"/>
<mx:Object label="AR" data="Little Rock"/>
</mx:List>
<mx:TextArea id="forChange" width="150"/>
</mx:Application>
In this example, you use two properties of the List control, selectedItem and
selectedIndex, in the event handler. Every change event updates the TextArea control with
the label of the selected item and the item’s index in the control.
The target property of the object passed to the event handler contains a reference to the List
control. You can reference any control property using the event’s currentTarget property.
The currentTarget.selectedItem field contains a copy of the selected item. If you
populate the List control with an Array of Strings, the currentTarget.selectedItem field
contains a String. If you populate it with an Array of Objects, the
currentTarget.selectedItem field contains the Object that corresponds to the selected
item, so, in this case, currentTarget.selectedItem.label refers to the selected item’s label
field.
Using a label function
You can pass a label function to the List control to provide logic that determines the text that
appears in the control. The label function must have the following signature:
labelFunction(item:Object):String
442
Using Data-Driven Controls
The item parameter passed in by the Label control contains the list item object. The function
must return the string to display in the List control.
NO T E
Most subclasses of ListBase also take a labelFunction property with the signature
described above. For the DataGrid and DataGridColumn controls, the method signature
is: labelFunction(item:Object, dataField:DataGridColumn):String
where item contains the DataGrid item object, and dataField specifies the DataGrid
column.
The following example uses a function to combine the values of the label and data fields for
each item for display in the List control:
<?xml version="1.0"?>
<!-- dpcontrols/ListLabelFunction.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
<mx:Script><![CDATA[
public function myLabelFunc(item:Object):String {
return item.data + ", " + item.label;
}
]]></mx:Script>
<mx:ArrayCollection id="myDP">
<mx:source>
<mx:Object label="AL" data="Montgomery"/>
<mx:Object label="AK" data="Juneau"/>
<mx:Object label="AR" data="Little Rock"/>
</mx:source>
</mx:ArrayCollection>
<mx:List dataProvider="{myDP}" labelFunction="myLabelFunc"/>
</mx:Application>
This example creates the following List control:
N OT E
This example uses an ArrayCollection object as the data provider. You should use
collections as the data providers if the data can change dynamically. For more
information, see Chapter 7, “Using Data Providers and Collections,” on page 161.
List control
443
Displaying DataTips
DataTips are similar to ToolTips, but display text when the mouse pointer hovers over a row
in a List control. Text in a List control that is longer than the control width is clipped on the
right side (or requires scrolling, if the control has scroll bars). DataTips can solve that problem
by displaying all of the text, including the clipped text, when the mouse pointer hovers over a
cell. If you enable data tips, they only appear for fields where the data is clipped. To display
DataTips, set the showDataTips property of a List control to true.
NO TE
To use DataTips with a DataGrid control, you must set the showDataTips property on the
individual DataGridColumns of the DataGrid.
The default behavior of the showDataTips property is to display the label text. However, you
can use the dataTipField and dataTipFunction properties to determine what is displayed
in the DataTip. The dataTipField property behaves like the labelField property; it
specifies the name of the field in the data provider to use as the DataTip for cells in the
column. The dataTipFunction property behaves like the labelFunction property; it
specifies the DataTip string to display for list items.
The following example sets the showDataTips property for a List control:
<mx:List id="myList" dataProvider="{myDP}" width="220" height="200"
showDataTips="true"/>
This example creates the following List control:
Displaying ScrollTips
You use ScrollTips to give users context about where they are in a list as they scroll through
the list. The tips appear only when you scroll; they don’t appear if you only hover the mouse
over the scroll bar. ScrollTips are useful when live scrolling is disabled (the liveScrolling
property is false) so scrolling does not occur until you release the scroll thumb. The default
value of the showScrollTips property is false.
444
Using Data-Driven Controls
The default behavior of the showScrollTips property is to display the index number of the
top visible item. You can use the scrollTipFunction property to determine what is
displayed in the ScrollTip. The scrollTipFunction property behaves like the
labelFunction property; it specifies the ScrollTip string to display for list items. You should
avoid going to the server to fill in a ScrollTip.
The following example sets the showScrollTips and scrollTipFunction properties of a
HorizontalList control. The scrollTipFunction property specifies a function that gets the
value of the description property of the current list item.
<mx:HorizontalList id="list" dataProvider="{album.photo}" width="100%"
itemRenderer="Thumbnail" columnWidth="108" height="100"
selectionColor="#FFCC00" liveScrolling="false" showScrollTips="true"
scrollTipFunction="scrollTipFunc"
change="currentPhoto=album.photo[list.selectedIndex]"/>
This code produces the following HorizontalList control:
Vertically aligning text in List control rows
You can use the verticalAlign style to vertically align text at the top, middle, or bottom of a
List row. The default value is top. You can also specify a value of middle or bottom.
The following example sets the verticalAlign property for a List control to bottom:
<mx:List id="myList" dataProvider="{myDP}" width="220" height="200"
verticalAlign="bottom"/>
Setting variable row height and wrapping List text
You can use the variableRowHeight property to make the height of List control rows
variable based on their content. The default value is false. If you set the
variableRowHeight property to true, the rowHeight property is ignored and the rowCount
property is read-only.
The following example sets the variableRowHeight property for a List control to true:
<mx:List id="myList" dataProvider="{myDP}" width="220" height="200"
variableRowHeight="true"/>
List control
445
You can use the wordWrap property in combination with the variableRowHeight property
to wrap text to multiple lines when it exceeds the width of a List row.
The following example sets the wordWrap and variableRowHeight properties to true:
<mx:List id="myList" dataProvider="{myDP}" width="220" height="200"
variableRowHeight="true" wordWrap="true"/>
This code produces the following List control:
Using a custom item renderer
A item renderer is the object that displays a List control’s data items. The simplest way to use
a custom item renderer is to specify an MXML component as the value of the itemRenderer
property. When you use an MXML component as a item renderer, it can contain multiple
levels of containers and controls. You can also use an ActionScript class as a custom item
renderer. For detailed information on custom item renderers, see Chapter 21, “Using Item
Renderers and Item Editors,” on page 851
The following example sets the itemRenderer property to an MXML component named
FancyCellRenderer. It also sets the variableRowHeight property to true because the MXML
component exceeds the default row height:
<mx:List id="myList1" dataProvider="{myDP}" width="220" height="200"
itemRenderer="FancyItemRenderer" variableRowHeight="true"/>
446
Using Data-Driven Controls
Specifying an icon to the List control
You can specify an icon to display with each List item, as the following example shows:
<?xml version="1.0"?>
<!-- dpcontrols/ListIcon.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
[Embed(source="assets/radioIcon.jpg")]
public var iconSymbol1:Class;
[Embed(source="assets/topIcon.jpg")]
public var iconSymbol2:Class;
]]>
</mx:Script>
<mx:List iconField="myIcon">
<mx:dataProvider>
<mx:Array>
<mx:Object label="AL" data="Montgomery" myIcon="iconSymbol1"/>
<mx:Object label="AK" data="Juneau" myIcon="iconSymbol2"/>
<mx:Object label="AR" data="Little Rock" myIcon="iconSymbol1"/>
</mx:Array>
</mx:dataProvider>
</mx:List>
</mx:Application>
In this example, you use the iconField property to specify the field of each item containing
the icon. You use the Embed metadata to import the icons, and then reference them in the List
control definition.
You can also use the iconFunction property to specify a function that determines the icon,
similar to the way that you can use the labelFunction property to specify a function that
determines the label text. The icon function must have the following signature:
iconFunction(item:Object):Class
The item parameter passed in by the Label control contains the list item object. The function
must return the icon class to display in the List control.
List control
447
The following example shows a List control that uses the iconFunction property to
determine the icon to display for each item in the list:
<?xml version="1.0"?>
<!-- dpcontrols/ListIconFunction.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
<mx:Script>
<![CDATA[
// Embed icons.
[Embed(source="assets/radioIcon.jpg")]
public var pavementSymbol:Class;
[Embed(source="assets/topIcon.jpg")]
public var normalSymbol:Class;
// Define data provider.
private var myDP: Array;
private function initList():void {
myDP = [
{Artist:'Pavement', Album:'Slanted and Enchanted',
Price:11.99},
{Artist:'Pavarotti', Album:'Twilight', Price:11.99},
{Artist:'Other', Album:'Other', Price:5.99}];
list1.dataProvider = myDP;
}
// Determine icon based on artist. Pavement gets a special icon.
private function myiconfunction(item:Object):Class{
var type:String = item.Artist;
if (type == "Pavement") {
return pavementSymbol;
}
return normalSymbol;
}
]]>
</mx:Script>
<mx:VBox >
<mx:List id="list1" initialize="initList()" labelField="Artist"
iconFunction="myiconfunction" />
</mx:VBox>
</mx:Application>
Alternating row colors in a List control
You can use the alternatingItemColors style property to specify an Array that defines the
color of each row in the List control. The Array must contain two or more colors. After using
all the entries in the Array, the List control repeats the color scheme.
448
Using Data-Driven Controls
The following example defines an Array with two entries, #66FFFF for light blue and
#33CCCC for a blue-gray. Therefore, the rows of the List control alternate between these two
colors. If you specify a three-color array, the rows alternate among the three colors, and so on.
<mx:List alternatingItemColors="[#66FFFF, #33CCCC]".../ >
List control user interaction
The user clicks individual list items to select them, and holds down the Control and Shift keys
while clicking to select multiple items. (You must set the allowMultipleSelection property
to true to allow multiple selecton.)
All mouse or keyboard selections broadcast a change event. For mouse interactions, the List
control broadcasts this event when the mouse button is released.
If you set the allowDragSelection property to true, the control scrolls up or down when
the user presses the mouse button over the one or more rows, holds the mouse button down,
drags the mouse outside the control, and then moves the mouse up and down.
A List control shows the number of records that fit in the display. Paging down through the
data displayed by a 10-line List control shows records 0-10, 9-18, 18-27, and so on, with one
line overlapping from one page to the next.
The List control has the following keyboard navigation features:
Key
Action
Up Arrow
Moves selection up one item.
Down Arrow
Moves selection down one item.
Page Up
Moves selection up one page.
Page Down
Moves selection down one page.
Home
Moves selection to the top of the list.
End
Moves selection to the bottom of the list.
Alphanumeric keys Jumps to the next item with a label that begins with the character typed.
Control
Toggle key. Allows for multiple (noncontiguous) selection and
deselection. Works with key presses, click selection, and drag selection.
Shift
Contiguous selection key. Allows for contiguous selections. Works with
key presses, click selection, and drag selection.
List control
449
HorizontalList control
The HorizontalList control displays a horizontal list of items. The HorizontalList control is
particularly useful in combination with a custom item renderer for displaying a list of images
and other data. For more information about custom item renderers, see Chapter 21, “Using
Item Renderers and Item Editors,” on page 851.
For complete reference information, see HorizontalList in Adobe Flex 2 Language Reference.
About HorizontaList controls
The contents of a HorizontalList control can look very similar to the contents of an HBox
container in which a Repeater object repeats components. However, performance of a
HorizontalList control can be better than the combination of an HBox container and a
Repeater object because the HorizontalList control only instantiates the objects that fit in its
display area. Scrolling in a HorizontalList can be slower than it is when using a Repeater
object. For more information about the Repeater object, see Chapter 26, “Dynamically
Repeating Controls and Containers,” on page 995.
The HorizontalList control always displays items from left to right. The control usually
contains a horizontal scroll bar, which lets users access all items in the list. An optional vertical
scroll bar lets users view items when the full height of the list items is unlikely to fit. The user
can select one or more items from the list, depending on the value of the
allowMultipleSelection property.
The following image shows a HorizontalList control:
The HorizontalList control has the following default sizing properties:
Property
Default value
Default size
Four columns, with the dimensions determined by the cell dimensions.
Minimum size
0
Maximum size
5000 by 5000
For complete reference information, see HorizontalList in Adobe Flex 2 Language Reference.
450
Using Data-Driven Controls
Creating a HorizontalList control
You use the <mx:HorizontalList> tag to define a HorizontalList control. 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 HorizontalList control shares many properties and methods with the List control; see
“List control” on page 440 for information on how to use several of these shared properties.
The HorizontalList control uses a list-based data provider. For more information, see “About
data providers” on page 162.
You specify the data for a HorizontalList control using the dataProvider property of the
<mx:HorizontalList> tag, as the following example shows:
<?xml version="1.0"?>
<!-- dpcontrols/HListDataProvider.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="450">
<mx:Script>
<![CDATA[
import mx.collections.*;
import mx.controls.Image;
private var catalog:ArrayCollection;
private static var cat:Array = [
"assets/usbfan.jpg", "assets/usbwatch.jpg",
"assets/007camera.jpg", "assets/radiowatch.jpg"
];
// Initialize the HorizontalList control by setting its
dataProvider
// property to an ArrayCollection containing the items parameter.
private function initCatalog(items:Array):void
{
catalog = new ArrayCollection(items);
myList.dataProvider = catalog;
}
]]>
</mx:Script>
<!-- A four-column HorizontalList.
The itemRenderer is a Flex Image control.
When the control is created, pass the cat array to the
initialization routine. -->
<mx:HorizontalList id="myList" columnWidth="100" rowHeight="100"
columnCount="4" itemRenderer="mx.controls.Image"
creationComplete="initCatalog(cat)"/>
</mx:Application>
HorizontalList control
451
In this example, you use the creationComplete event to populate the data provider with an
ArrayCollection of image files, and the itemRenderer property to specify the Image control
as the item renderer. (Note that you use the full package name of the control in the
assignment because the code does not import the mx.controls package.) The HorizontalList
control then displays the four images specified by the data provider.
The following examples are based on the Flex Explorer application included in Flex 2.
The HorizontalListDemo.mxml example displays a catalog of product images in a
HorizontalList control. The item renderer for the HorizontalList control is an MXML
component named Thumbnail.
<?xml version="1.0"?>
<!-- dpcontrols/HorizontalListDemo.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
backgroundAlpha="0" creationComplete="srv.send()">
<mx:Script>
<![CDATA[
import mx.utils.ArrayUtil;
]]>
</mx:Script>
<mx:HTTPService id="srv" url="assets/catalog.xml" useProxy="false"/>
<mx:ArrayCollection id="catalogAC"
source="{mx.utils.ArrayUtil.toArray(srv.lastResult.catalog.product)}"/>
<mx:HorizontalList dataProvider="{catalogAC}"
width="100%" itemRenderer="Thumbnail"/>
</mx:Application>
452
Using Data-Driven Controls
The following example shows the Thumbnail.mxml MXML component that is used as the
item renderer in the product catalog application. In this example, you define the item
renderer to contain three controls: an Image control and two Label controls. These controls
examine the data object passed to the item renderer to determine the content to display. For
more information about custom item renderers, see Chapter 21, “Using Item Renderers and
Item Editors,” on page 851.
<?xml version="1.0"?>
<!-- dpcontrols/Thumbnail.mxml -->
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml"
width="165" height="120" verticalAlign="middle" verticalGap="0"
verticalScrollPolicy="off">
<mx:CurrencyFormatter id="cf"/>
<mx:Image id="img" height="100" width="50" source="../{data.image}"/>
<mx:VBox width="100%" paddingTop="0" horizontalGap="4">
<mx:Label text="{data.name}" fontWeight="bold"/>
<mx:Label text="{cf.format(data.price)}" fontWeight="bold"/>
</mx:VBox>
</mx:HBox>
HorizontalList control user interaction
The user clicks individual list items to select them, and holds down the Control and Shift keys
while clicking to select multiple items.
All mouse or keyboard selections broadcast a change event. For mouse interactions, the
HorizontalList control broadcasts this event when the mouse button is released. When the
user drags the mouse over the items and then outside the control, the control scrolls up or
down.
A HorizontalList control shows the number of records that fit in the display. Paging through a
four list shows records 0-4, 5-8, and so on, with no overlap from one page to the next.
Keyboard navigation
The HorizontalList control has the following keyboard navigation features:
Key
Action
Page Up
Moves selection to the left one page.
Left Arrow
Moves selection to the left one item.
Down Arrow
Moves selection right one item.
Page Down
Moves selection to the right one page.
Home
Moves selection to the beginning of the list.
HorizontalList control
453
Key
Action
End
Moves selection to the end of the list.
Control
Toggle key. Allows for multiple (noncontiguous) selection and deselection
when the allowMultipleSelection property is set to true. Works with key
presses, click selection, and drag selection.
Shift
Contiguous selection key. Allows for contiguous selections when
allowMultipleSelection is set to true. Works with key presses, click
selection, and drag selection.
TileList control
The TileList control displays a tiled list of items. The items are tiled in vertical columns or
horizontal rows. The TileList control is particularly useful in combination with a custom item
renderer for displaying a list of images and other data. The default item renderer for the
TileList control is TileListItemRenderer, which, by default, displays text of the data provider’s
label field and any icon. For more information about custom item renderers, see Chapter 21,
“Using Item Renderers and Item Editors,” on page 851.
For complete reference information, see TileList in Adobe Flex 2 Language Reference.
About the TileList control
The contents of a TileList control can look very similar to the contents of a Tile container in
which a Repeater object repeats components. However, performance of a TileList control can
be better than the combination of a Tile container and a Repeater object because the TileList
control only instantiates the objects that fit in its display area. Scrolling in a TileList can be
slower than it is when using a Repeater object. For more information about the Repeater
object, see Chapter 26, “Dynamically Repeating Controls and Containers,” on page 995.
The TileList control displays a number of items laid out in equally sized tiles. It often contains
a scroll bar on one of its axes to access all items in the list depending on the direction
orientation of the list. The user can select one or more items from the list depending on the
value of the allowMultipleSelection property.
454
Using Data-Driven Controls
The TileList control lays out its children in one or more vertical columns or horizontal rows,
starting new rows or columns as necessary. The direction property determines the primary
direction of the layout. The valid values for the direction property are and horizontal
(default) and vertical for a layout. In a horizontal layout the tiles are filled in row by row
with each row filling the available space in the control. If there are more tiles than fit in the
display area, the horizontal control has a vertical scroll. In a vertical layout, the tiles are
filled in column by column in the available vertical space, and the control may have a
horizontal scroll bar.
The following image shows a TileList control:
The TileList control has the following default sizing properties:
Property
Default value
Default size
Four columns and four rows. Using the default item renderer, each cell is
50 by 50 pixels, and the total size is 200 by 200 pixels.
Minimum size
0
Maximum size
5000 by 5000
For complete reference information, see TileList in Adobe Flex 2 Language Reference.
Creating a TileList control
You use the <mx:TileList> tag to define a TileList control. 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.
TileList control
455
The TileList control shares many properties and methods with the List control; see “List
control” on page 440 for information on how to use several of these shared properties. The
TileList control uses a list-based data provider. For more information, see “About data
providers” on page 162.
You specify the data for a TileList control using the dataProvider property of the
<mx:TileList> tag, as the following example shows:
<?xml version="1.0"?>
<!-- dpcontrols/TileListDataProvider.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="initData();" >
<mx:Script>
<![CDATA[
import mx.controls.Button;
import mx.collections.*;
private var listArray:Array=[
{label: "item0", data: 0},{label: "item1", data:
{label: "item2", data: 2},{label: "item3", data:
{label: "item4", data: 4},{label: "item5", data:
{label: "item6", data: 6},{label: "item7", data:
{label: "item8", data: 8}];
[Bindable]
public var TileListdp:ArrayCollection;
1},
3},
5},
7},
private function initData():void {
TileListdp = new ArrayCollection(listArray);
}
]]>
</mx:Script>
<mx:TileList dataProvider="{TileListdp}"
itemRenderer="mx.controls.Button"/>
</mx:Application>
In this example, you populate the data provider with an ArrayCollection that contains an
Array of strings defining labels and data values. You then use the itemRenderer property to
specify a Button control as the item renderer. The Button controls display the data provider
label values. The TileList control displays nine Button controls with the specified labels.
456
Using Data-Driven Controls
The next example is the TileListDemo.mxml file from the Flex Explorer sample application;
this example shows the MXML code for a catalog application that displays a set of product
images in a TileList control. The item renderer for the TileList control is an MXML
component named Thumbnail. In this example, you define the item renderer to contain three
controls: an Image control and two Label controls. These controls examine the data object
passed to the item renderer to determine the content to display. For more information about
custom item renderers, see Chapter 21, “Using Item Renderers and Item Editors,” on
page 851.
<?xml version="1.0"?>
<!-- dpcontrols/TileListDemo.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
backgroundAlpha="0" creationComplete="srv.send()">
<mx:HTTPService id="srv" url="assets/catalog.xml" useProxy="false"/>
<mx:TileList dataProvider="{srv.lastResult.catalog.product}"
height="100%" width="100%" itemRenderer="Thumbnail"
rowHeight="130" columnWidth="175"/>
</mx:Application>
The Thumbnail.mxml MXML component that is used as the item renderer in the product
catalog application is identical to the one in “HorizontalList control” on page 450. For more
information about custom item renderers, see Chapter 21, “Using Item Renderers and Item
Editors,” on page 851.
TileList control user interaction
The user clicks individual list items to select them, and holds down the Control and Shift keys
while clicking to select multiple items.
All mouse or keyboard selections broadcast a change event. For mouse interactions, the
TileList control broadcasts this event when the mouse button is released. When the user drags
the mouse over the items and then outside the control, the control scrolls up or down.
TileList control
457
Keyboard navigation
The TileList control has the following keyboard navigation features:
Key
Action
Up Arrow
Moves selection up one item. If the control direction is vertical, and the
current item is at the top of a column, moves to the last item in the previous
column; motion stops at the first item in the first column.
Down Arrow
Moves selection down one item.If the control direction is vertical, and the
current item is at the bottom of a column, moves to the first item in the next
column; motion stops at the last item in the last column.
Right Arrow
Moves selection to the right one item. If the control direction is horizontal,
and the current item is at the end of a row, moves to the first item in the next
row; motion stops at the last item in the last column.
Left Arrow
Moves selection to the left one item. If the control direction is horizontal,
and the current item is at the beginning of a row, moves to the last item in
the previous row; motion stops at the first item in the first row.
Page Up
Moves selection up one page. For a single-page control, moves the
selection to the beginning of the list.
Page Down
Moves selection down one page. For a single-page control, moves the
selection to the end of the list.
Home
Moves selection to the beginning of the list.
End
Moves selection to the end of the list.
Control
Toggle key. Allows for multiple (noncontiguous) selection and deselection
when allowMultipleSelection is set to true. Works with key presses, click
selection, and drag selection.
Shift
Contiguous selection key. Allows for contiguous selections when
allowMultipleSelection is set to true. Works with key presses, click
selection, and drag selection.
ComboBox control
The ComboBox control is a drop-down list from which the user can select a single value. Its
functionality it is very similar to that of the SELECT form element in HTML.
For complete reference information, see ComboBox in Adobe Flex 2 Language Reference.
458
Using Data-Driven Controls
About the ComboBox control
The following image shows a ComboBox control:
In its editable state, the user can type text directly into the top of the list, or select one of the
preset values from the list. In its noneditable state, as the user types a letter, the drop-down list
opens and scrolls to the value that most closely matches the one being entered; matching is
only performed on the first letter that the user types.
If the drop-down list hits the lower boundary of the application, it opens upward. If a list item
is too long to fit in the horizontal display area, it is truncated to fit. If there are too many
items to display in the drop-down list, a vertical scroll bar appears.
The ComboBox control has the following default sizing properties:
Property
Default value
Default size
Wide enough to accommodate the longest entry in the drop-down list in
the display area of the main control, plus the drop-down button. When the
drop-down list is not visible, the default height is based on the label text
size.
The default drop-down list height is five rows, or the number of entries in
the drop-down list, whichever is smaller. The default height of each entry
in the drop-down list is 22 pixels.
Minimum size
0
Maximum size
5000 by 5000.
dropdownWidth
The width of the ComboBox control.
rowCount
5
Creating a ComboBox control
You use the <mx:ComboBox> tag to define a ComboBox 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.
The ComboBox control uses a list-based data provider. For more information, see “About data
providers” on page 162.
ComboBox control
459
You specify the data for the ComboBox control using the dataProvider property of the
<mx:ComboBox> tag. The data provider should be an Array, or a class that implements the
ICollectionView or IList interface; often it is an ArrayCollection. For more information on
data providers and collections see Chapter 7, “Using Data Providers and Collections,” on
page 161.
In a simple case for creating a ComboBox control, you specify the property using an
child tag, and use an <mx:ArrayCollection> tag to define the entries
as an ArrayCollection whose source is an Array of Strings, as the following example shows:
<mx:dataProvider>
<?xml version="1.0"?>
<!-- dpcontrols/ComboBoxSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:ComboBox>
<mx:ArrayCollection>
<mx:String>AK</mx:String>
<mx:String>AL</mx:String>
<mx:String>AR</mx:String>
</mx:ArrayCollection>
</mx:ComboBox>
</mx:Application>
This example shows how you can take advantages of MXML defaults. You do not have to use
an <mx:dataProvider> tag, because dataProvider is the default property of the ComboBox
control. Similarly, you do not have to use an <mx:source> tag inside the
<mx:ArrayCollection> tag because source is the default property of the ArrayCollection
class. Finally, you do not have to specify an <mx:Array> tag for the source array.
The data provider can also contain objects with multiple fields, as in the following example:
<?xml version="1.0"?>
<!-- dpcontrols/ComboBoxMultiple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:ComboBox>
<mx:ArrayCollection>
<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>
460
Using Data-Driven Controls
If the data source is an array of strings, as in the first example, the ComboBox displays strings
as the items in the drop-down list. If the data source consists of objects, the ComboBox, by
default, uses the contents of the label field. You can, however, override this behavior, as
described in “Specifying ComboBox labels” on page 463.
The index of items in the ComboBox control is zero-based, which means that values are 0, 1,
2, ... , n - 1, where n is the total number of items. The value of the item is its label text.
Using events with ComboBox controls
You typically use events to handle user interaction with a ComboBox control.
The ComboBox control broadcasts a change event (flash.events.Event class with a type
property value of flash.events.Event.CHANGE) when the value of the control’s
selectedIndex or selectedItem property changes due to the following user actions:
■
If the user closes the drop-down list using a mouse click, Enter key, or Control+Up key,
and the selected item is different from the previously selected item.
■
If the drop-down list is currently closed, and the user presses the Up, Down, Page Up, or
Page Down key to select a new item.
■
If the ComboBox control is editable, and the user types into the control, Flex broadcasts a
change event each time the text field of the control changes.
The ComboBox control broadcasts an mx.events.DropdownEvent with a type
mx.events.DropdownEvent.OPEN (open) and mx.events.DropdownEvent.CLOSE (close)
when the ComboBox control opens and closes. For detailed information on these and other
ComboBox events, see ComboBox in Adobe Flex 2 Language Reference.
ComboBox control
461
The following example displays information from ComboBox events:
<?xml version="1.0"?>
<!-- dpcontrols/ComboBoxEvent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
<mx:Script>
<![CDATA[
import flash.events.Event;
import mx.events.DropdownEvent;
// Display the type of event for open and close events.
private function dropEvt(event:DropdownEvent):void {
forChange.text+=event.type + "\n";
}
// Display a selected item's label field and index for change
events.
private function changeEvt(event:Event):void {
forChange.text+=event.currentTarget.selectedItem.label + " " +
event.currentTarget.selectedIndex + "\n";
}
]]>
</mx:Script>
<mx:ComboBox open="dropEvt(event)" close="dropEvt(event)"
change="changeEvt(event)" >
<mx:ArrayCollection>
<mx:Object label="AL" data="Montgomery"/>
<mx:Object label="AK" data="Juneau"/>
<mx:Object label="AR" data="Little Rock"/>
</mx:ArrayCollection>
</mx:ComboBox>
<mx:TextArea id="forChange" width="150" height="100%"/>
</mx:Application>
If you populate the ComboBox control with an Array of Strings, the
currentTarget.selectedItem field contains a String. If you populate it with an Array of
Objects, the currentTarget.selectedItem field contains the Object that corresponds to
the selected item, so, in this case, currentTarget.selectedItem.label refers to the
selected item object’s label field.
In this example, you use two properties of the ComboBox control, selectedItem and
selectedIndex, in the event handlers. Every change event updates the TextArea control with
the label of the selected item and the item’s index in the control, and every open or close
event appends the event type.
462
Using Data-Driven Controls
Specifying ComboBox labels
If the ComboBox data source is an array of strings, the control displays the string for each
item. If the data source is contains Objects, by default, the ComboBox control expects each
object to contain a property named label that defines the text that appears in the ComboBox
control for the item. If each Object does not contain a label property, you can use the
labelField property of the ComboBox control to specify the property name, as the
following example shows:
<mx:ComboBox open="dropEvt(event)" close="dropEvt(event)"
change="changeEvt(event)" labelField="state">
<mx:ArrayCollection>
<mx:Object state="AL" capital="Montgomery"/>
<mx:Object state="AK" capital="Juneau"/>
<mx:Object state="AR" capital="Little Rock"/>
</mx:ArrayCollection>
</mx:ComboBox>
To make the event handler in the section “Using events with ComboBox controls”
on page 461 display the state ID and capital, you would modify the change event handler to
use a property named state, as the following example shows:
private function changeEvt(event) {
forChange.text=event.currentTarget.selectedItem.state + " " +
event.currentTarget.selectedItem.capital + " " +
event.currenttarget.selectedIndex;
}
You can also specify the ComboBox labels using a label function, as described in Using a label
function on page 442.
ComboBox control
463
Populating a ComboBox control using variables and models
Flex lets you populate the data provider of a ComboBox control from an ActionScript variable
definition or from a Flex data model. Each element of the data provider must contain a string
label, and can contain one or more fields with additional data. The following example
populates two ComboBox controls; one from an ArrayCollection variable that it populates
directly from an Array, the other from an ArrayCollection that it populates from an array of
items in an <MX:Model> tag.
<?xml version="1.0"?>
<!-- dpcontrols/ComboBoxVariables.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="initData();">
<mx:Script>
<![CDATA[
import mx.collections.*
private var COLOR_ARRAY:Array=
[{label:"Red", data:"#FF0000"},
{label:"Green", data:"#00FF00"},
{label:"Blue", data:"#0000FF"}];
// Declare an ArrayCollection variable for the colors.
// Make it Bindable so it can be used in bind
// expressions ({colorAC}).
[Bindable]
public var colorAC:ArrayCollection;
// Initialize colorAC ArrayCollection variable from the Array.
// Use an initialize event handler to initialize data variables
// that do not rely on components, so that the initial values are
// available when the controls that use them are constructed.
//See the mx:ArrayCollection tag, below, for a second way to
//initialize an ArrayCollection.
private function initData():void {
colorAC=new ArrayCollection(COLOR_ARRAY);
}
]]>
</mx:Script>
<!-- This example shows two different ways to
structure a Model. -->
<mx:Model id="myDP">
<obj>
<item label="AL" data="Montgomery"/>
<item>
<label>AK</label>
<data>Juneau</data>
</item>
<item>
<label>AR</label>
464
Using Data-Driven Controls
<data>Little Rock</data>
</item>
</obj>
</mx:Model>
<!-- Create a stateAC ArrayCollection that uses as its source an Array of
the item elements from the myDP model.
This technique and the declaration and initialization code used for
the colorAC variable are alternative methods of creating and
initializing the ArrayCollection. -->
<mx:ArrayCollection id="stateAC" source="{myDP.item}"/>
<mx:ComboBox dataProvider="{colorAC}"/>
<mx:ComboBox dataProvider="{stateAC}"/>
</mx:Application>
This example uses a simple model. However, you can populate the model from an external
data source or define a custom data model class in ActionScript. For more information on
using data models, see Chapter 39, “Storing Data,” on page 1269.
You can use remote data providers to supply data to your ComboBox control. For example,
when a web service operation returns an Array of strings, you can use the following format to
display each string as a row of a ComboBox control:
<mx:ArrayCollection id=”resultAC”
source=”mx.utils.ArrayUtil.toArray(service.operation.lastResult);”
<mx:ComboBox dataProvider="{resultAC}" />
For more information on using remote data providers, see “Using remote data providers”
on page 213.
ComboBox control user interaction
An ArrayCollection control can be noneditable or editable, as specified by the Boolean
editable property. In a noneditable ComboBox control, a user can make a single selection
from a drop-down list. In an editable ComboBox control, the portion button of the control is
a text field that the user can enter text directly into or can populate by selecting an item from
the drop-down list. When the user makes a selection in the ComboBox control list, the label
of the selection is copied to the text field at the top of the ComboBox control.
When a ComboBox control (and not the drop-down box) has focus and is editable, all
keystrokes go to the text field and are handled according to the rules of the TextInput control
(see “TextInput control” on page 393), with the exception of the Control+Down key
combination, which opens the drop-down list. When the drop-down list is open, you can use
the Up and Down keys to navigate in the list and the Enter key to select an item from the list.
ComboBox control
465
When a ComboBox control has focus and is noneditable, alphanumeric keystrokes move the
selection up and down the data provider to the next item with the same first character and
display the label in the text field. If the drop-down list is open, the visible selection moves to
the selected item.
You can also use the following keys to control a noneditable ComboBox control when the
drop-down list is not open:
Key
Description
Control+Down
Opens the drop-down list and gives it focus.
Down
Moves the selection down one item.
End
Moves the selection to the bottom of the collection.
Home
Moves the selection to the top of the collection.
Page Down
Displays the item that would be at the end bottom of the drop-down list.
If the current selection is a multiple of the rowCount value, displays the
item that rowCount -1 down the list, or the last item. If the current
selection is the last item in the data provider, does nothing,.
Page Up
Displays the item that would be at the top of the drop-down. If the
current selection is a multiple of the rowCount value, displays the item
that rowCount -1 up the list, or the first item. If the current selection is the
first item in the data provider, does nothing,
Up
Moves the selection up one item.
When the drop-down list of a non-editable ComboBox control has focus, alphanumeric
keystrokes move the selection up and down the drop-down list to the next item with the same
first character. You can also use the following keys to control a drop-down list when it is open:
Key
Description
Control+Up
Closes the drop-down list and returns focus to the ComboBox control.
Down
Moves the selection down one item.
End
Moves the selection to the bottom of the collection.
Enter
Closes the drop-down list and returns focus to the ComboBox control.
Escape
Closes the drop-down list and returns focus to the ComboBox control.
Home
Moves the selection to the top of the collection.
Page Down
Moves to the bottom of the visible list. If the current selection is at the
bottom of the list, moves the current selection to the top of the displayed
list and displays the next rowCount-1 items, if any. If there current selection
is the last item in the data provider, does nothing,.
466
Using Data-Driven Controls
Key
Description
Page Up
Moves to the top of the visible list. If the current selection is at the top of the
list, moves the current selection to the bottom of the displayed list and
displays the previous rowCount-1 items, if any. If the current selection is the
first item in the data provider, does nothing,.
Shift+Tab
Closes the drop-down list and moves the focus to the previous object in the
DisplayList.
Tab
Closes the drop-down list and moves the focus to the next object in the
DisplayList.
Up
Moves the selection up one item.
DataGrid control
The DataGrid control is a list that can display more than one column of data. It is a formatted
table of data that lets you set editable table cells, and is the foundation of many data-driven
applications.
This topic describes how to create and use DataGrid controls, including how to sort the data.
It does not cover information on the following topics, which are often important for creating
advanced data grid controls:
■
How to format the information in each DataGrid cell and control how users enter data in
the cells; for information on these topics, see Chapter 21, “Using Item Renderers and Item
Editors,” on page 851.
■
How to drag objects to and from the data grid; for information on this topic, see Chapter
29, “Using the Drag and Drop Manager,” on page 1081.
For complete reference information, see DataGrid in Adobe Flex 2 Language Reference.
About the DataGrid control
The DataGrid control provides the following features:
■
Resizable, sortable, and customizable column layouts, including hidable columns
■
Optional customizable column and row headers, including optionally wrapping header
text
■
Columns that the user can resize and reorder at run time
■
Selection events
■
Ability to use a custom item renderer for any column
■
Support for paging through data
DataGrid control
467
■
Locked rows and columns that do not scroll
The following image shows a DataGrid control:
Rows are responsible for rendering items. Each row is laid out vertically below the previous
one. Columns are responsible for maintaining the state of each visual column; columns
control width, color, and size.
The DataGrid control has the following default sizing properties:
Property
Default value
Default size
If the columns are empty, the default width is 300 pixels. If the columns
contain information but define no explicit widths, the default width is 100
pixels per column. The DataGrid width is sized to fit the width of all
columns, if possible.
The default number of displayed rows, including the header is 7, and each
row, by default, is 20 pixels high.
Minimum size
0
Maximum size
5000 by 5000
Creating a DataGrid control
You use the <mx:DataGrid> tag to define a DataGrid 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.
The DataGrid control uses a list-based data provider. For more information, see “About data
providers” on page 162.
468
Using Data-Driven Controls
You specify the data for the DataGrid control using the dataProvider property. You can
specify data in several different ways. In the simplest case for creating a DataGrid control, you
use the <mx:dataProvider> property subtag with <mx:ArrayCollection>, and
<mx:Object> tags to define the entries as an ArrayCollection of Objects. Each Object defines
a row of the DataGrid control, and properties of the Object define the column entries for the
row, as the following example shows:
<?xml version="1.0"?>
<!-- dpcontrols/DataGridSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:DataGrid>
<mx:ArrayCollection>
<mx:Object>
<mx:Artist>Pavement</mx:Artist>
<mx:Price>11.99</mx:Price>
<mx:Album>Slanted and Enchanted</mx:Album>
</mx:Object>
<mx:Object>
<mx:Artist>Pavement</mx:Artist>
<mx:Album>Brighten the Corners</mx:Album>
<mx:Price>11.99</mx:Price>
</mx:Object>
</mx:ArrayCollection>
</mx:DataGrid>
</mx:Application>
This example shows how you can take advantages of MXML defaults. You do not have to use
an <mx:dataProvider> tag, because dataProvider is the default property of the DataGrid
control. Similarly, you do not have to use an <mx:source> tag inside the
<mx:ArrayCollection> tag because source is the default property of the ArrayCollection
class. Finally, you do not have to specify an <mx:Array> tag for the source array.
You can also define the objects using properties directly in the Object tags, as the following
example shows:
<?xml version="1.0"?>
<!-- dpcontrols/DataGridSimpleAttributes.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:DataGrid>
<mx:ArrayCollection>
<mx:Object Artist="Pavement"
Album="Slanted and Enchanted" Price="11.99" />
<mx:Object Artist="Pavement"
Album="Brighten the Corners" Price="11.99" />
</mx:ArrayCollection>
</mx:DataGrid>
</mx:Application>
DataGrid control
469
The column names displayed in the DataGrid control are the property names of the Array
Objects. By default, the columns are in alphabetical order by the property names. Different
Objects can define their properties in differing orders. If an Array Object omits a property, the
DataGrid control displays an empty cell in that row.
Specifying columns
Each column in a DataGrid control is represented by a DataGridColumn object. You use the
columns property of the DataGrid control and the <mx:DataGridColumn> tag to select the
DataGrid columns, specify the order in which to display them, and set additional properties.
You can also use the DataGridColumn class visible property to hide and redisplay columns,
as described in “Hiding and displaying columns” on page 471.
For complete reference information for the <mx:DataGridColumn> tag, see DataGridColumn
in Adobe Flex 2 Language Reference.
You specify an Array element to the <mx:columns> child tag of the <mx:DataGrid> tag, as the
following example shows:
<?xml version="1.0"?>
<!-- dpcontrols/DataGridSpecifyColumns.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
<mx:DataGrid>
<mx:ArrayCollection>
<mx:Object Artist="Pavement" Price="11.99"
Album="Slanted and Enchanted" />
<mx:Object Artist="Pavement"
Album="Brighten the Corners" Price="11.99" />
</mx:ArrayCollection>
<mx:columns>
<mx:DataGridColumn dataField="Album" />
<mx:DataGridColumn dataField="Price" />
</mx:columns>
</mx:DataGrid>
</mx:Application>
In this example, you only display the Album and Price columns in the DataGrid control. You
can reorder the columns as well, as the following example shows:
<mx:columns>
<mx:DataGridColumn dataField="Price" />
<mx:DataGridColumn dataField="Album" />
</mx:columns>
In this example, you specify that the Price column is the first column in the DataGrid control,
and that the Album column is the second.
470
Using Data-Driven Controls
You can also use the <mx:DataGridColumn> tag to set other options. The following example
uses the headerText property to set the name of the column to a value different than the
default name of Album, and uses the width property to set the album name column wide
enough to display the full album names:
<mx:columns>
<mx:DataGridColumn dataField="Album" width="200" />
<mx:DataGridColumn dataField="Price" headerText="List Price" />
</mx:columns>
Hiding and displaying columns
If you might display a column at some times, but not at others, you can specify the
DataGridColumn class visible property to hide or show the column. The following
example lets you hide or show the album price by clicking a button:
<?xml version="1.0"?>
<!-- dpcontrols/DataGridVisibleColumn.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
<mx:DataGrid id="myDG" width="350">
<mx:dataProvider>
<mx:ArrayCollection>
<mx:source>
<mx:Object Artist="Pavement" Price="11.99"
Album="Slanted and Enchanted" />
<mx:Object Artist="Pavement"
Album="Brighten the Corners" Price="11.99" />
</mx:source>
</mx:ArrayCollection>
</mx:dataProvider>
<mx:columns>
<mx:DataGridColumn dataField="Artist" />
<mx:DataGridColumn dataField="Album" />
<mx:DataGridColumn id="price" dataField="Price" visible="false"/>
</mx:columns>
</mx:DataGrid>
<!-- The column id property specifies the column to show.-->
<mx:Button label="Toggle Price Column"
click="price.visible = !price.visible;" />
</mx:Application>
DataGrid control
471
Passing data to a DataGrid control
Flex lets you populate a DataGrid control from an ActionScript variable definition or from a
Flex data model. The following example populates a DataGrid control by using a variable:
<?xml version="1.0"?>
<!-- dpcontrols/DataGridPassData.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="initData()">
<mx:Script>
<![CDATA[
import mx.collections.*;
private var DGArray:Array = [
{Artist:'Pavement', Album:'Slanted and Enchanted', Price:11.99},
{Artist:'Pavement', Album:'Brighten the Corners', Price:11.99}];
[Bindable]
public var initDG:ArrayCollection;
//Initialize initDG ArrayCollection variable from the Array.
//You can use this technique to convert an HTTPService,
//WebService, or RemoteObject result to ArrayCollection.
public function initData():void {
initDG=new ArrayCollection(DGArray);
}
]]>
</mx:Script>
<mx:DataGrid id="myGrid" width="350" height="200"
dataProvider="{initDG}" >
<mx:columns>
<mx:DataGridColumn dataField="Album" />
<mx:DataGridColumn dataField="Price" />
</mx:columns>
</mx:DataGrid>
</mx:Application>
In this example, you bind the variable initDG to the <mx:dataProvider> property. You can
still specify a column definition event when using data binding. For a description of using a
model as a data provider, see “Populating a ComboBox control using variables and models”
on page 464.
472
Using Data-Driven Controls
Handling events in a DataGrid control
The DataGrid control and the DataGridEvent class define several event types that let you
respond to user interaction. For example, Flex broadcasts mx.events.ListEvent class event with
a type property value of mx.events.ListEvent.ITEM_CLICK ("itemClick") when a user
clicks an item in a DataGrid control. You can handle this event as the following example
shows:
<?xml version="1.0"?>
<!-- dpcontrols/DataGridEvents.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.events.ListEvent;
private function itemClickEvent(event:ListEvent):void {
clickColumn.text=String(event.columnIndex);
clickRow.text=String(event.rowIndex);
eventType.text=event.type;
}
]]>
</mx:Script>
<mx:DataGrid id="myGrid" width="350" height="150"
itemClick="itemClickEvent(event);">
<mx:ArrayCollection>
<mx:Object Artist="Pavement" Price="11.99"
Album="Slanted and Enchanted" />
<mx:Object Artist="Pavement" Album="Brighten the Corners"
Price="11.99" />
</mx:ArrayCollection>
</mx:DataGrid>
<mx:TextArea id="clickColumn" />
<mx:TextArea id="clickRow" />
<mx:TextArea id="eventType" />
</mx:Application>
In this example, you use the event handler to display the column index, row index, and event
type in three TextArea controls.
The index of columns in the DataGrid control is zero-based, meaning values are 0, 1, 2, ... ,
n - 1, where n is the total number of columns. Row items are also indexed starting at 0.
Therefore, if you select the first item in the second row, this example displays 0 in the first
Text Area control for the column index, and 1 in the second TextArea control for the item
index in the column.
DataGrid control
473
To access the selected item in the event handler, you can use the currentTarget property of
the event object, and the selectedItem property of the DataGrid control, as the following
code shows:
var selectedArtist:String=event.currentTarget.selectedItem.Artist;
The currentTarget property of the object passed to the event handler contains a reference to
the DataGrid control. You can reference any control property using currentTarget followed
by a period and the property name. The currentTarget.selectedItem field contains the
selected item.
Sorting data in DataGrid controls
The DataGrid control supports displaying sorted data in two ways:
■
By default, the control displays data in the sorted order of its underlying data provider
collection. Therefore you can use the collection Sort and SortField classes to control the
order of the rows.
■
By default, users can sort the display by clicking the column headers. Clicking the column
header initially sorts the display in descending order of the entries in the selected column,
and clicking the header again reverses the sort order. You can disable sorting an entire
DataGrid Control or individual columns.
For detailed information on using the Sort and SortField classes, see “Sorting and filtering
data for viewing” on page 177.
Determining the initial DataGrid sort order
To specify the initial DataGrid sort order, you sort the data provider. While a number of
approaches can work, the following technique takes best advantage of the built in features of
Flex collections:
■
Use an object that implements the ICollectionView interface, such as an ArrayCollection,
in the dataProvider property of your DataGrid. Specify a Sort object in the data
provider object’s the sort field
■
Use the Sort object to control the order of the rows in the dataProvider object.
For an example that sets an initial, multicolumn sort on a DataGrid, see “Example: Sorting a
DataGrid on multiple columns” on page 476.
474
Using Data-Driven Controls
Controlling user sorting of DataGrid displays
Three DataGrid and DataGridColumn properties control how users can sort the order of a
data
■
The DataGrid sortableColumns property is a global switch that enables user sorting of
the DataGrid display by clicking column headings. The default this property is true.
■
The DataGridColumn class sortable property specifies whether users can sort an
individual column. The default this property is true.
■
The DataGridColumn class sortCompareFunction property lets you specify a custom
comparison function. This property sets the compare property of the default SortField
class object that the DataGrid uses to sort the grid when users click the headers. It lets you
specify the function that compares two objects and determines which would be higher in
the sort order, without requiring you to explicitly create a Sort object on your data
provider. For detailed information on the comparison function signature and behavior, see
sortCompareFunction in Adobe Flex 2 Language Reference.
By default, the DataGrid class uses its own sort code to control how the data gets sorted when
the user clicks a column. To override this behavior, you create a headerRelease event handler
to handle the DataGridEvent class event that is generated when the user clicks the column
header. This event handler must do the following:
1.
Use the event object’s columnIndex property to determine the clicked column.
2.
Establish a Sort object with a set of SortField objects based on the clicked column and any
other rules that you need to control the sorting order.
3.
Apply the Sort object to the data provider ICollectionView.
4.
Call the DataGridEvent class event object’s preventDefault() method to prevent the
DataGrid from doing a default column sort.
NO T E
If you specify a labelFunction property, you must also specify a sortCompareFunction
function. The Computed Columns example in Flex Explorer shows this use.
The following example shows how to use the headerRelease event handler to do multi-column
sorting when a user clicks a DataGrid column header.
DataGrid control
475
Example: Sorting a DataGrid on multiple columns
The following example shows how you can use a collection with a Sort object to determine an
initial multi-column sort and to control how the columns sort when you click the headers.
The data grid is initially sorted by in-stock status first, artist second, and album name, third.
If you click any heading, that column becomes the primary sort criterion, the previous
primary criterion becomes the second criterion, and the previous secondary criterion becomes
the third criterion.
<?xml version="1.0"?>
<!-- dpcontrols/DataGridSort.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="initDP();" width="550" height="400">
<mx:Script>
<![CDATA[
import mx.events.DataGridEvent;
import mx.collections.*;
// Declare storage variables and initialize the simple variables.
// The data provider collection.
private var myDPColl:ArrayCollection;
// The Sort object used to sort the collection.
[Bindable]
private var sortA:Sort;
// The sort fields used to determine the sort.
private var sortByInStock:SortField;
private var sortByArtist:SortField;
private var sortByAlbum:SortField;
private var sortByPrice:SortField;
// The data source that populates the collection.
private var myDP:Array = [
{Artist:'Pavement', Album:'Slanted and Enchanted',
Price:11.99, InStock: true},
{Artist:'Pavement', Album:'Crooked Rain, Crooked Rain',
Price:10.99, InStock: false},
{Artist:'Pavement', Album:'Wowee Zowee',
Price:12.99, InStock: true},
{Artist:'Asphalt', Album:'Brighten the Corners',
Price:11.99, InStock: false},
{Artist:'Asphalt', Album:'Terror Twilight',
Price:11.99, InStock: true},
{Artist:'Asphalt', Album:'Buildings Meet the Sky',
Price:14.99, InStock: true},
{Artist:'Other', Album:'Other', Price:5.99, InStock: true}
];
//Initialize the DataGrid control with sorted data.
private function initDP():void {
476
Using Data-Driven Controls
//Create an ArrayCollection backed by the myDP array of data.
myDPColl = new ArrayCollection(myDP);
//Create a Sort object to sort the ArrrayCollection.
sortA = new Sort();
//Initialize SortField objects for all valid sort fields:
// A true second parameter specifies a case-insensitive sort.
// A true third parameter specifies descending sort order.
// A true fourth parameter specifies a numeric sort.
sortByInStock = new SortField("InStock", true, true);
sortByArtist = new SortField("Artist", true);
sortByAlbum = new SortField("Album", true);
sortByPrice = new SortField("Price", true, false, true);
// Sort the grid using the InStock, Artist, and Album fields.
sortA.fields=[sortByInStock, sortByArtist, sortByAlbum];
myDPColl.sort=sortA;
// Refresh the collection view to show the sort.
myDPColl.refresh();
// Initial display of sort fields
tSort0.text = "First Sort Field: InStock";
tSort1.text = "Second Sort Field: Artist";
tSort2.text = "Third Sort Field: Album";
// Set the ArrayCollection as the DataGrid data provider.
myGrid.dataProvider=myDPColl;
// Set the DataGrid row count to the array length,
// plus one for the header.
myGrid.rowCount=myDPColl.length +1;
}
// Re-sort the DataGrid control when the user clicks a header.
private function headRelEvt(event:DataGridEvent):void {
// The new third priority was the old second priority.
sortA.fields[2] = sortA.fields[1];
tSort2.text = "Third Sort Field: " + sortA.fields[2].name;
// The new second priority was the old first priority.
sortA.fields[1] = sortA.fields[0];
tSort1.text = "Second Sort Field: " + sortA.fields[1].name;
// The clicked column determines the new first priority.
if (event.columnIndex==0) {
sortA.fields[0] = sortByArtist;
} else if (event.columnIndex==1) {
sortA.fields[0] = sortByAlbum;
} else if (event.columnIndex==2) {
sortA.fields[0] = sortByPrice;
} else {
sortA.fields[0] = sortByInStock;}
tSort0.text = "First Sort Field: " + sortA.fields[0].name;
// Apply the updated sort fields and re-sort.
myDPColl.sort=sortA;
// Refresh the collection to show the sort in the grid.
DataGrid control
477
myDPColl.refresh();
// Prevent the DataGrid from doing a default column sort.
event.preventDefault();
}
]]>
</mx:Script>
<!-- The Data Grid control.
By default the grid and its columns can be sorted by clicking.
The headerRelease event handler overrides the default sort
behavior. -->
<mx:DataGrid id="myGrid" width="100%"
headerRelease="headRelEvt(event);">
<mx:columns>
<mx:DataGridColumn minWidth="120" dataField="Artist" />
<mx:DataGridColumn minWidth="200" dataField="Album" />
<mx:DataGridColumn width="75" dataField="Price" />
<mx:DataGridColumn width="75" dataField="InStock"
headerText="In Stock"/>
</mx:columns>
</mx:DataGrid>
<mx:VBox>
<mx:Label id="tSort0" text="First Sort Field: "/>
<mx:Label id="tSort1" text="Second Sort Field: "/>
<mx:Label id="tSort2" text="Third Sort Field: "/>
</mx:VBox>
</mx:Application>
DataGrid control user interaction
The DataGrid control responds to mouse and keyboard activity. The response to a mouse
click or key press depends on whether a cell is editable. A cell is editable when the editable
properties of the DataGrid control and the DataGridColumn containing the cell are both
true. Clicking within an editable cell directs focus to that cell. Clicking a noneditable cell has
no effect on the focus.
Users can modify the DataGrid control appearance in the following ways:
■
If the value of the sortableColumns property is true, the default value, clicking within a
column header causes the DataGrid control to be sorted based on the column’s cell values.
■
If the value of the draggableColumns property is true, the default value, clicking and
holding the mouse button within a column header, dragging horizontally, and releasing
the mouse button moves the column to new location.
■
If the value of the resizableColumns property is true, the default value, clicking in the
area between columns permits column resizing.
478
Using Data-Driven Controls
Keyboard navigation
The DataGrid control has the following keyboard navigation features:
Key
Action
Enter
Return
Shift+Enter
When a cell is in editing state, commits change, and moves editing to the cell
on the same column, next row down or up, depending on whether Shift is
pressed.
Tab
Moves focus to the next editable cell, traversing the cells in row order. If at the
end of the last row, advances to the next element in the parent container that
can receive focus.
Shift+Tab
Moves focus to the previous editable cell. If at the beginning of a row,
advances to the end of the previous row. If at the beginning of the first row,
advances to the previous element in the parent container that can receive
focus.
Up Arrow
Home
Page Up
If editing a cell, shifts the cursor to the beginning of the cell’s text. If the cell is
not editable, moves selection up one item.
Down Arrow
End
Page Down
If editing a cell, shifts the cursor to the end of the cell’s text. If the cell is not
editable, moves selection down one item.
Control
Toggle key. If you set the DataGrid control allowMultipleSelection property
to true, allows for multiple (noncontiguous) selection and deselection. Works
with key presses, click selection, and drag selection.
Shift
Contiguous select key. If you set the DataGrid control allowMultipleSelection
property to true, allows for contiguous selections. Works with key presses,
click selection, and drag selection.
Tree control
The Tree control lets a user view hierarchical data arranged as an expandable tree.
For complete reference information, see Tree in Adobe Flex 2 Language Reference. For
information on hierarchical data providers, see “Using hierarchical data providers”
on page 197.
This topic describes how to create and use Tree controls. It does not cover information on the
following topics, which are often important for using advanced Tree controls:
■
How to format the information in each Tree node and control how users enter data in the
nodes; for information on these topics, see Chapter 21, “Using Item Renderers and Item
Editors,” on page 851.
Tree control
479
■
How to drag objects to and from the Tree control; for information on this topic, see
Chapter 29, “Using the Drag and Drop Manager,” on page 1081.
About Tree Controls
A Tree control is a hierarchical structure of branch and leaf nodes. Each item in a tree is called
a node and can be either a leaf or a branch. A branch node can contain leaf or branch nodes,
or can be empty (have no children). A leaf node is an end point in the tree.
By default, a leaf is represented by a text label beside a file icon and a branch is represented by
a text label beside a folder icon with a disclosure triangle that a user can open to expose
children.
The following image shows a Tree control:
The Tree control has the following default sizing properties:
Property
Default value
Default size
wide enough to accommodate the icon, label, and expansion triangle, if any,
of the widest node in the first 7 displayed (uncollapsed) rows, and seven
rows high, where each row is 20 pixels in height. If a scroll bar is required,
the width of the scroll bar is not included in the width calculations.
Minimum size
0
Maximum size
5000 by 5000
Creating a Tree control
You define a Tree control in MXML using the <mx:Tree> tag. The Tree control is derived
from the List control and takes all of the properties and methods of the List control. For more
information about using the List control, see “List control” on page 440. Specify an id value
if you intend to refer to a control elsewhere in your MXML, either in another tag or in an
ActionScript block.
480
Using Data-Driven Controls
The Tree control normally gets its data from a hierarchical data provider, such as XML. If the
Tree represents dynamically changing data, you use an object that implements the
ICollectionView interface, such as ArrayCollection or XMLListCollection.
The Tree control uses a data descriptor to parse and manipulate the data provider contents. By
default, the Tree control uses a DefaultDataDescriptor class descriptor, but you can create
your own class and specify it in the Menu control’s dataDescriptor property.
The DefaultDataDescriptor class supports the following types of data:
XML
A string containing valid XML text, or any of the following objects containing valid
E4X format XML data: <mx:XML> or <mx:XMLList> compile-time tag, or an XML or
XMLList object.
Other objects
An array of items, or an object that contains an array of items, where a node’s
children are contained in an item named children.
Collections
An object that implements the ICollectionView interface (such as the
ArrayCollection or XMLListCollection classes) and whose data source conforms to the
structure specified in either of the previous bullets. The DefaultDataDescriptor class includes
code to handle collections efficiently. Always use a collection as the data provider if the data in
the menu changes dynamically; otherwise the Tree control might display obsolete data.
The DefaultDataDescriptor class also supports using an <mx:Model> tag as a data provider for
a menu, but all leaf nodes must have the name children; As a general rule, it is a better
programming practice to use the <mx:XML> or <mx:XMLList> tags when you need a Tree data
provider that uses binding.
For more information on hierarchical objects and data descriptors, including a detailed
description of the formats supported by the DefaultDataDescriptor, see “Data descriptors and
hierarchical data provider structure” on page 197.
Tree control
481
The following code contains a single Tree control that defines the tree shown in the image in
“Tree control” on page 479. This uses an XMLListCollection wrapper around an
<mx:XMLList> tag. By using an XMLListCollection, you can modify the underlying XML
data provider by changing the contents of the MailBox XMLListCollection, and the Tree
control will represent the changes to the data. This example also does not use the
<mx:dataProvider> tag because dataProvider is the default property of the Tree control.
<?xml version="1.0"?>
<!-- dpcontrols/TreeSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Tree id="tree1" labelField="@label" showRoot="true" width="160">
<mx:XMLListCollection id="MailBox">
<mx:XMLList>
<folder label="Mail">
<folder label="INBOX"/>
<folder label="Personal Folder">
<Pfolder label="Business" />
<Pfolder label="Demo" />
<Pfolder label="Personal" isBranch="true" />
<Pfolder label="Saved Mail" />
</folder>
<folder label="Sent" />
<folder label="Trash" />
</folder>
</mx:XMLList>
</mx:XMLListCollection>
</mx:Tree>
</mx:Application>
The tags that represent tree nodes in the XML data can have any name. The Tree control
reads the XML and builds the display hierarchy based on the nested relationship of the nodes.
For information on valid XML structure, see “Using hierarchical data providers” on page 197.
Some data providers have a single, top level called a root node. Other data providers are lists of
nodes and do not have a root node. In some cases, you might not want to display the root
node as the Tree root. To prevent the tree from displaying the root node, specify the showRoot
property to false; doing this does not affect the data provider contents, only the Tree
display. You can only specify a false showRoot property for data providers that have roots,
that is, XML and Object-based data providers.
A branch node can contain multiple child nodes, and, by default, appears as a folder icon with
a disclosure triangle that lets users open and close the folder. Leaf nodes appear by default as
file icons and cannot contain child nodes.
482
Using Data-Driven Controls
When a Tree control displays a node of a non-XML data provider, by default, it displays the
value of the label property of the node as the text label. When you use an E4X XML-based
data provider, however, you must specify the label field, even if the label is identified by an
attribute named “label”. To specify the label field, use the labelField property; for example,
if the label field is the label attribute, specify labelField="@label".
Handling Tree control events
You typically use events to respond to user interaction with a Tree control. Since the Tree
control is derived from the List control, you can use all of the events defined for the List
control. The Tree control also dispatches several Event and TreeEvent class events, including
Event.change and TreeEvent.itemOpen. The following example defines event handlers for
the change and nodeOpen events:
<?xml version="1.0"?>
<!-- dpcontrols/TreeEvents.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import flash.events.*;
import mx.events.*;
import mx.controls.*;
private function changeEvt(event:Event):void {
var theData:String = ""
if ([email protected]) {
theData = " Data: " + [email protected];
}
forChange.text = [email protected] +
theData;
}
private function itemOpenEvt(event:TreeEvent):void {
forOpen.text = [email protected];
}
]]>
</mx:Script>
<mx:Tree id="XMLtree1" width="150" height="170"
labelField="@label" itemOpen="itemOpenEvt(event);"
change= "changeEvt(event);">
<mx:XMLListCollection id="MailBox">
<mx:XMLList>
<node label="Mail" data="100">
<node label="Inbox" data="70"/>
<node label="Personal Folder" data="10">
<node label="Business" data="2"/>
Tree control
483
<node label="Demo" data="3"/>
<node label="Personal" data="0" isBranch="true" />
<node label="Saved Mail" data="5" />
</node>
<node label="Sent" data="15"/>
<node label="Trash" data="5"/>
</node>
</mx:XMLList>
</mx:XMLListCollection>
</mx:Tree>
<mx:Label text="Change Event:" />
<mx:TextArea id="forChange" width="150" />
<mx:Label text="Open Event:" />
<mx:TextArea id="forOpen" width="150" />
</mx:Application>
In this example, you define event listeners for the change and itemOpen events. The Tree
control broadcasts the change event when the user selects a tree item, and broadcasts the
itemOpen event when a user opens a branch node. For each event, the event handler displays
the label and the data property, if any, in a TextArea control. In this example, only the
Business and SavedMail nodes define a data value.
Expanding a tree node
By default, the Tree control displays the root nodes of the tree when it first opens. If you want
to expand a node of the tree when the tree opens, you can use the expandItem() method of
the Tree control. The following change to the example in “Handling Tree control events”
on page 483 calls the expandItem() method as part of the Tree control’s creationComplete
event listener to expand the root node of the tree:
<mx:Script>
<![CDATA[
.
.
.
private function initTree():void {
XMLTree1.expandItem(MailBox.getItemAt(0), true);
forOpen.text=XMLTree1.openItems[0][email protected];
}
]]>
</mx:Script>
<mx:Tree id="tree1" ... creationComplete="initTree();" >
...
</mx:Tree>
484
Using Data-Driven Controls
This example must use the Tree control’s creationComplete event, not the initialize
event, because the data provider is not fully initialized and available until the
creationComplete event.
The Tree control openItems property is an Array containing all expanded tree nodes. The
following line in the example code displays the label of the first (and only) open item in the
tree:
forOpen.text=XMLTree1.openItems[0][email protected];
In this example, however, you could also get the openItems box to indicate the initial open
item by setting the expandItem() method to dispatch an itemOpen event. You can do this by
specifying the fourth, optional parameter of the expandItem() method to true. The true
fourth parameter causes the tree to dispatch an open event when the item opens. The
following example shows the use of the fourth parameter:
XMLTree1.expandItem(MailBox.getItemAt(0), true, false, true);
Specifying Tree control icons
The Tree control provides four techniques for specifying node icons:
■
The folderOpenIcon, folderClosedIcon, and defaultLeafIcon properties
■
Data provider node icon fields
■
The setItemItcon() method
■
The iconFunction property
Using icon properties
You can use the folderOpenIcon, folderClosedIcon, and defaultLeafIcon properties to
control the Tree control icons. For example, the following code specifies a default icon, and
icons for the open and closed states of branch nodes:
<mx:Tree folderOpenIcon="@Embed(source='open.jpg')"
folderClosedIcon="@Embed(source='closed.jpg')"
defaultLeafIcon="@Embed(source='def.jpg')">
Tree control
485
Using icon fields
You can specify an icon displayed with each Tree leaf when you populate it using XML, as the
following example shows:
<?xml version="1.0"?>
<!-- dpcontrols/TreeIconField.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
[Bindable]
[Embed(source="assets/radioIcon.jpg")]
public var iconSymbol1:Class;
[Bindable]
[Embed(source="assets/topIcon.jpg")]
public var iconSymbol2:Class;
]]>
</mx:Script>
<mx:Tree iconField="@icon" labelField="@label" showRoot="false"
width="160">
<mx:XMLList>
<node label="New">
<node label="HTML Document" icon="iconSymbol2"/>
<node label="Text Document" icon="iconSymbol2"/>
</node>
<node label="Close" icon="iconSymbol1"/>
</mx:XMLList>
</mx:Tree>
</mx:Application>
In this example, you use the iconField property to specify the field of each item containing
the icon. You use the Embed metadata to import the icons, then reference them in the XML
definition. You cannot specify icons for individual branch nodes; instead you must use the
Tree control’s folderOpenIcon, folderClosedIcon properties, each of which specifies an
icon to use for all open or closed branches.
486
Using Data-Driven Controls
Using the setItemIcon() method
You can use the setItemIcon() method to specify the icon, or both the open and closed
icons for a tree item. This method lets you dynamically specify and change icons for
individual branches and nodes. For details on this function see setItemIcon() in ActionScript
3.0 Language Reference. The following example sets the open and closed node icon for the first
branch node and the icon for the second branch (that does not have any leaves):
<?xml version="1.0"?>
<!-- dpcontrols/TreeItemIcon.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
[Bindable]
[Embed(source="assets/radioIcon.jpg")]
public var iconSymbol1:Class;
[Bindable]
[Embed(source="assets/topIcon.jpg")]
public var iconSymbol2:Class;
private function setIcons():void {
myTree.setItemIcon(myTree.dataProvider.getItemAt(0),
iconSymbol1, iconSymbol2);
myTree.setItemIcon(myTree.dataProvider.getItemAt(1),
iconSymbol2, null);
}
]]>
</mx:Script>
<mx:Tree id="myTree" labelField="@label" showRoot="false"
width="160" initialize="setIcons();">
<mx:XMLList>
<node label="New">
<node label="HTML Document"/>
<node label="Text Document"/>
</node>
<node label="Close"/>
</mx:XMLList>
</mx:Tree>
</mx:Application>
Tree control
487
Using an icon function
You can use the Tree control iconFunction property to specify a function that dynamically
sets all icons for the tree. For information on using the iconFunction property in Flex
controls, see “Specifying an icon to the List control” on page 447.
Tree user interaction
You can let users edit tree control labels. The controls also support several keyboard
navigation and editing keys.
Editing a node label at run time
Set the editable property of the Tree control to true to make node labels editable at run
time. To edit a node label, the user selects the label, and then enters a new label or edits the
existing label text.
To support label editing, the Tree control’s List superclass uses the following events. These
events belong to the ListEvent class:
Event
Description
itemEditBegin
Dispatched when the editedItemPosition property has been set and the
cell can be edited.
itemEditEnd
Dispatched when cell editing session ends for any reason.
itemFocusIn
Dispatched when tree node gets the focus: when a user selects the
label or tabs to it.
itemFocusOut
Dispatched when a label loses focus.
itemClick
Dispatched when a user clicks on an item in the control.
These events are commonly used in custom item editors. For more information see Chapter
21, “Using Item Renderers and Item Editors,” on page 851.
488
Using Data-Driven Controls
Using the keyboard to edit labels
If you set the Tree editable property to true, you can use the following keys to edit labels:
Key
Description
Down Arrow
Page Down
End
Moves the caret to the end of the label.
Up Arrow
Page Up
Home
Moves the caret to the beginning of the label.
Right Arrow
Moves the caret forward one character.
Left Arrow
Moves the caret backwards one character.
Enter
Ends editing and moves selection to next visible node, which can then be
edited. At the last node, selects the label.
Shift Enter
Ends editing and moves selection to previous visible node, which can
then be edited. At the first node, selects the label.
Escape
Cancels the edit, restores the text, and changes the row state from editing
to selected.
TAB
When in editing mode, accepts the current changes, selects the row
below, and goes into editing mode with the label text selected. If at the last
element in the tree or not in editing mode, sends focus to the next control.
Shift-TAB
When in editing mode, accepts the current changes, selects the row
above, and goes into editing mode. If at the first element in the tree or not
in editing mode, sends focus to the previous control.
Tree control
489
Tree Navigation keys
When a Tree control is not editable and has focus from clicking or tabbing, you use the
following keys to control it:
Key
Description
Down Arrow
Moves the selection down one. When the Tree control gets focus, use the
Down arrow to move focus to the first node.
Up Arrow
Moves the selection up one item.
Right Arrow
Opens a selected branch node. If a branch is already open, moves to the
first child node.
Left Arrow
Closes a selected branch node. If a leaf node or a closed branch node is
currently selected, selects the parent node.
Spacebar or
* (Asterisk on
numeric keypad)
Opens or closes a selected branch node (toggles the state).
+ (Plus sign on
numeric keypad)
Open a selected branch node.
- (Minus sign on
numeric keypad)
Closes a selected branch node.
Control + Arrow
keys
Move focus, but does not select a node. Use the Spacebar to select a
node.
End
Moves the selection to the bottom of the list.
Home
Moves the selection to the top of the list.
Page down
Moves the selection down one page.
Page up
Moves the selection up one page.
Control
If the allowMultipleSelection property is true, allows multiple
noncontiguous selections.
Shift
If the allowMultipleSelection property is true, allows multiple contiguous
selections.
For information on using keys to edit tree labels, see “Using the keyboard to edit labels”
on page 489.
490
Using Data-Driven Controls
13
CHAPTER 13
Introducing Containers
Containers provide a hierarchical structure that lets you control the layout characteristics of
child components. You can use containers to control sizing and positioning of all children, or
to control navigation among multiple child containers.
This topic introduces the two types of containers: layout and navigator. This topic contains an
overview of container usage, including layout rules, and examples of how to use and configure
containers.
Contents
About containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
Using containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
Using scroll bars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .507
Using Flex coordinates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
Creating and managing component instances at run time . . . . . . . . . . . . . . . . . . . . 516
About containers
A container defines a rectangular region of the drawing surface of Adobe Flash Player. Within
a container, you define the components, both controls and containers, that you want to
appear within the container. Components defined within a container are called children of the
container. Adobe Flex provides a wide variety of containers, ranging from simple boxes
through panels and forms, to elements such as accordions or tabbed navigators that provide
built-in navigation among child containers.
At the root of a Flex application is a single container, called the Application container, that
represents the entire Flash Player drawing surface. This Application container holds all other
containers and components.
491
A container has predefined rules to control the layout of its children, including sizing and
positioning. Flex defines layout rules to simplify the design and implementation of rich
Internet applications, while also providing enough flexibility to let you create a diverse set of
applications.
About container layout
Containers have predefined navigation and layout rules, so you do not have to spend time
defining these. Instead, you can concentrate on the information that you deliver, and the
options that you provide for your users, and not worry about implementing all the details of
user action and application response. In this way, Flex provides the structure that lets you
quickly and easily develop an application with a rich set of features and interactions.
Predefined layout rules also offer the advantage that your users soon grow accustomed to
them. That is, by standardizing the rules of user interaction, your users do not have to think
about how to navigate the application, but can instead concentrate on the content that the
application offers.
Different containers support different layout rules:
■
All containers, except the Canvas container, support automatic layout. With this type of
layout you do not specify the position of the children of the container. Instead, you
control the positions by selecting the container type; by setting the order of the container’s
children; and by specifying properties, such as gaps, and controls, such as Spacers. For
example, to lay out children horizontally in a box, you use the HBox container.
■
The Canvas container, and optionally the Application and Panel containers, use absolute
layout, where you explicitly specify the children’s x and y positions. Alternatively, you can
use constraint-based layout to anchor the sides or center of the children relative to the
parent.
Absolute layout provides a greater level of control over sizing and positioning than does
automatic layout; for example, you can use it to overlay one control on another. But absolute
layout provides this control at the cost of making you specify positions in detail.
For more information on layout, see Chapter 8, “Sizing and Positioning Components,” on
page 221.
492
Introducing Containers
About layout containers and navigator containers
Flex defines two types of containers:
Layout containers control
the sizing and positioning of the child controls and child
containers defined within them. For example, a Grid layout container sizes and positions its
children in a layout similar to an HTML table. Layout containers also include graphical
elements that give them a particular style or reflect their function. The DividedBox container,
for example, has a bar in the center that users can drag to change the relative sizes of the two
box divisions. The TitleWindow control has an initial bar that can contain a title and status
information. For more information on these containers, see Chapter 15, “Using Layout
Containers,” on page 553.
Navigator containers control user movement, or navigation, among multiple child
containers. The individual child containers, not the navigator container, control the layout
and positioning of their children. For example, an Accordion navigator container lets you
construct a multipage form from multiple Form layout containers. For more information, see
Chapter 16, “Using Navigator Containers,” on page 627.
Using containers
The rectangular region of a container encloses its content area, the area that contains its child
components. The size of the region around the content area is defined by the container
padding and the width of the container border. A container has top, bottom, left, and right
padding, each of which you can set to a pixel width. A container also has properties that let
you specify the type and pixel width of the border. The following image shows a container and
its content area, padding, and borders:
Left padding
Right padding
Top padding
Container
Content area
Bottom padding
Using containers
493
Although you can create an entire Flex application by using a single container, typical
applications use multiple containers. For example, the following image shows an application
that uses three layout containers:
Parent HBox
layout container
Child VBox
layout container
Components
Components
Child VBox
layout container
In this example, the two VBox (vertical box) layout containers are nested within an HBox
(horizontal box) layout container and are referred to as children of the HBox container.
The HBox container arranges its children in a single horizontal row and oversees the sizing
and positioning characteristics of the VBox containers. For example, you can control the
distance, or gap, between children in a container by using the horizontalGap and
verticalGap properties.
A VBox container arranges its children in a single vertical stack, or column, and oversees the
layout of its own children. The following image shows the preceding example with the
outermost container changed to a VBox layout container:
Parent VBox
layout container
Components
Child VBox
layout container
Components
Child VBox
layout container
In this example, the outer container is a VBox container, so it arranges its children in a vertical
column.
494
Introducing Containers
The primary use of a layout container is to arrange its children, where the children are either
controls or other containers. The following image shows a simple VBox container that has
three child components:
TextInput control
Button control
TextArea control
In this example, a user enters a ZIP code into the TextInput control, and then clicks the
Button control to see the current temperature for the specified ZIP code in the TextArea
control.
Flex supports form-based applications through its Form layout container. In a Form
container, Flex can automatically align labels, uniformly size TextInput controls, and display
input error notifications. The following image shows a Form container:
Form containers can take advantage of the Flex validation mechanism to detect input errors
before the user submits the form. By detecting the error, and letting the user correct it before
submitting the form to a server, you eliminate unnecessary server connections. The Flex
validation mechanism does not preclude you from performing additional validation on the
server. For more information on Form containers, see “Form, FormHeading, and FormItem
layout containers” on page 570. For more information on validators, see Chapter 40,
“Validating Data,” on page 1281.
Using containers
495
Navigator containers, such as the TabNavigator and Accordion containers, have built-in
navigation controls that let you organize information from multiple child containers in a way
that makes it easy for a user to move through it. The following image shows an Accordion
container:
Accordion buttons
You use the Accordion buttons to move among the different child containers. The Accordion
container defines a sequence of child panels, but displays only one panel at a time. To navigate
a container, the user clicks on the navigation button that corresponds to the child panel that
they want to access.
Accordion containers support the creation of multistep procedures. The preceding image
shows an Accordion container that defines four panels of a complex form. To complete the
form, the user enters data into all four panels. Accordion containers let users enter
information in the first panel, click the Accordion button to move to the second panel, and
then move back to the first if they want to edit the information. For more information, see
“Accordion navigator container” on page 639.
496
Introducing Containers
Flex containers
The following table describes the Flex containers:
Container
Type
Description
For more
information
Accordion
Navigator Organizes information in a series of “Accordion navigator
container” on page 639
child panels, where one panel is
active at any time.
Application
ControlBar
Layout
Holds components that provide
global navigation and application
commands. Can be docked at the
top of an Application container.
Box (HBox and
VBox)
Layout
“Box, HBox, and VBox
Displays content in a uniformly
layout containers”
spaced row or column. An HBox
on page 559
container horizontally aligns its
children; a VBox container vertically
aligns its children.
Canvas
Layout
Defines a container in which you
must explicitly position its children.
ControlBar
Layout
Places controls at the lower edge of “ControlBar layout
a Panel or TitleWindow container.
container” on page 562
DividedBox
(HDividedBox
and
VDividedBox)
Layout
Lays out its children horizontally or
vertically, much like a Box
container, except that it inserts an
adjustable divider between the
children.
“DividedBox,
HDividedBox, and
VDividedBox layout
containers”
on page 567
Form
Layout
Arranges its children in a standard
form format.
“Form, FormHeading,
and FormItem layout
containers”
on page 570
Grid
Layout
Arranges children as rows and
columns of cells, much like an
HTML table.
“Grid layout container”
on page 594
Panel
Layout
Displays a title bar, a caption, a
border, and its children.
“Panel layout container”
on page 601
TabNavigator
Navigator Displays a container with tabs to let “TabNavigator
users switch between different
container” on page 634
content areas.
“ApplicationControlBar
layout container”
on page 564
“Canvas layout
container” on page 554
Using containers
497
Container
Type
Description
For more
information
Tile
Layout
Defines a layout that arranges its
“Tile layout container”
children in multiple rows or columns. on page 606
TitleWindow
Layout
Displays a popup window that
contains a title bar, a caption,
border, a close button, and its
children. The user can move and
resize the container.
ViewStack
Navigator Defines a stack of containers that
“ViewStack navigator
displays a single container at a time. container” on page 628
“TitleWindow layout
container” on page 609
Class hierarchy for containers
Flex containers are implemented as a hierarchy in an ActionScript class library, as the
following image shows:
Sprite
UIComponent
Container
All Containers
All containers are derived from the ActionScript classes Sprite, UIComponent, and Container,
and therefore inherit the properties, methods, styles, effects, and events of their superclasses.
Some containers are subclasses of other containers; for example, the ApplicationControlBar is
a subclass of the ControlBar container. For a complete reference, see Adobe Flex 2 Language
Reference.
498
Introducing Containers
Container example
The following image shows a Flex application that uses a Panel container with three child
controls, where the Panel container lays out its children vertically:
The following MXML code creates this example:
<?xml version="1.0"?>
<!-- containers\intro\Panel3Children.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Panel title="My Application"
layout="vertical" horizontalAlign="center"
paddingLeft="10" paddingRight="10"
paddingTop="10" paddingBottom="10">
<mx:TextInput id="myinput" text="enter zip code"/>
<mx:Button id="mybutton" label="GetWeather"/>
<mx:TextArea id="mytext" height="20"/>
</mx:Panel>
</mx:Application>
The following image shows the preceding example implemented by using a Panel container
with a horizontal layout:
Using containers
499
The only difference between these examples is the container type and the increased width of
the Application container caused by the horizontal layout, as the following code shows:
<?xml version="1.0"?>
<!-- containers\intro\Panel3ChildrenHoriz.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Panel title="My Application"
layout="horizontal"
paddingLeft="10" paddingRight="10"
paddingTop="10" paddingBottom="10">
<mx:TextInput id="myinput" text="enter zip code"/>
<mx:Button id="mybutton" label="GetWeather"/>
<mx:TextArea id="mytext" height="20"/>
</mx:Panel>
</mx:Application>
To actually retrieve weather information, you must set up a web service, pass it the entered
ZIP code from a click event, and use the returned information to populate the TextArea
control.
Using container events
All containers and components support events, as described in the following sections.
Event overview
The following events are dispatched only by containers:
Dispatched after a child is added to the container.
■
childAdd
■
childRemove
■
childIndexChange
■
scroll
Dispatched before a child is removed from the container.
Dispatched after a child’s index in the container has changed.
Dispatched when the user manually scrolls the container.
The first three events are dispatched for each of the container’s children, and the last is
dispatched when the container scrolls. For detailed information on these events, see Container
in Adobe Flex 2 Language Reference.
The following events are dispatched only by Application containers:
Dispatched after the application has been initialized, processed
by the LayoutManager, and attached to the display list. This is the last event dispatched
during an application’s startup sequence. It is later than the application’s
creationComplete event, which gets dispatched before the preloader has been removed
and the application has been attached to the display list.
■
applicationComplete
■
error
500
Dispatched when an uncaught error occurs anywhere in the application.
Introducing Containers
The following events are dispatched by all components after they are added to or removed
from a container:
■
add Dispatched by a component after the component has been added to its container
and the parent and the child are in a consistent state. This event is dispatched after the
container has dispatched the childAdd event and all changes that need to be made as
result of the addition have happened.
■
Dispatched by a component after the component has been removed from its
parent container. This event is dispatched after the container has dispatched the
childRemove event and all changes that need to be made as result of the removal have
happened.
remove
Several events are dispatched for all components, but need special consideration for
containers, particularly navigator containers such as TabNavigator, where some children
might not be created when the container is created. These events include the following:
■
preinitialize Dispatched when the component has been attached to its parent
container, but before the component has been initialized, or any of its children have been
created. In most cases, this event is dispatched too early for an application to use to
configure a component.
■
initialize
■
creationComplete
Dispatched when a component has finished its construction and its
initialization properties have been set. At this point, all of the component’s immediate
children have been created (they have at least dispatched their preinitialize event), but
they have not been laid out. Exactly when initialize events are dispatched depends on the
container’s creation policy, as described later in this section.
Dispatched when the component, and all of its child components,
and all of their children, and so on have been created, laid out, and are visible.
For information on the initialize and creationComplete events, see “About the initialize
and creationComplete events” on page 502. For information on the remaining events, see
Container in Adobe Flex 2 Language Reference.
About the creation policy
Containers have a creationPolicy property that specifies when its children are created. By
default, containers have an creation policy of ContainerCreationPolicy.AUTO, which
means that the container delays creating descendants until they are needed, a process which is
known as deferred instantiation. (A container’s default creation policy is derived from its
parent’s instantiation policy, and the Application container has a default policy of
ContainerCreationPolicy.AUTO.
Using containers
501
An auto creation policy produces the best startup time because fewer components are created
initially. For navigator containers such as the ViewStack, TabNavigator, and Accordion, an
ContainerCreationPolicy.AUTO creation policy means that the container creates its direct
children immediately, but waits to create the descendants of each child until the child needs to
be displayed. As a result, only the initially required child or children of a container get
processed past the preinitialization stage.
A creation policy of ContainerCreationPolicy.ALL requires all of a container’s children to
be fully created and initialized before the container is initialized. For detailed information on
creation policies, see Chapter 6, “Improving Startup Performance,” in Building and Deploying
Flex 2 Applications.
About the initialize and creationComplete events
Flex dispatches the initialize event for a container after it attaches all the container’s direct
child controls and the container’s initially required children have dispatched a
preinitialize event.
When a container or control dispatches the initialize event, its initial properties have been
set, but its width and height have not yet been calculated, and its position has not been
calculated. The initialize event is useful for configuring a container’s children. For
example, you can use the a container’s initialize event to programmatically add children or
set a container scroll bar’s styles. You can use a container or component’s initialize
initialize event to initialize the data provider for a control.
Flex dispatches the creationComplete event for a container when those children that are
initially required are fully processed and drawn on the screen, including all required children
of the children and so on. Create a listener for the creationComplete event, for example, if
you must have the children’s dimensions and positions in your event handler. Do not use the
creationComplete event for actions that set layout properties, as doing so results in excess
processing time.
To better understand the order in which Flex dispatches events, consider the following
application outline.
Application
OuterVBox
InnerVBox1
InnerVBoxLabel1
InnerVBox2
InnerVBoxLabel2
502
Introducing Containers
The preinitialize, initialize, and creationComplete events for the containers and
controls are dispatched in the following order. The indentation corresponds to the
indentation in the previous outline:
OuterVBox preinitialize
InnerVBox1 preinitialize
InnerVBox1Label preinitialize
InnerVBox1Label initialize
InnerVBox1 initialize
InnerVBox2 preinitialize
InnerVBox2Label preinitialize
InnerVBox2Label initialize
InnerVBox2 initialize
OuterVBox initialize
InnerBox1Label creationComplete
InnerVBox2Label creationComplete
InnerVBox1 creationComplete
InnerVBox2 creationComplete
OuterVBox creationComplete
Notice that for the terminal controls, such as the Label controls, the controls are preinitialized
and then immediately initialized. For containers, preinitialization starts with the outermost
container and works inward on the first branch, and then initialization works outward on the
same branch. This process continues until all initialization is completed. Then, the
creationComplete event is dispatched first by the leaf components, and then by their
parents, and so on until the application dispatches the creationComplete event.
If you change the OuterVBox container to a ViewStack with a creationPolicy property set
to auto, the events would look as follows:
OuterViewStack preinitialize
InnerVBox1 preinitialize
InnerVBox2 preinitialize
OuterViewStack initialize
InnerBox1Label preinitialize
InnerBox1Label initialize
InnerVBox1 initialize
InnerBox1Label creationComplete
InnerVBox1 creationComplete
OuterViewStack creationComplete
In this case, the second VBox is preinitialized only, because it does not have to be displayed.
Notice that when a navigator container dispatches the initialize event, its children exist
and have dispatched the preinitialize event, but its children have not dispatched the
initialize event because they have not yet created their own children. For more
information on the creationPolicy property, see Chapter 6, “Improving Startup
Performance,” in Building and Deploying Flex 2 Applications.
Using containers
503
The initialize event is useful with a container that is an immediate child of a navigator
container with an ContainerCreationPolicy.AUTO creation policy. For example, by default,
when a ViewStack is initialized, the first visible child container dispatches an initialize
event. Then, as the user moves to each additional child of the container, the event gets
dispatched for that child container.
The following example defines an event listener for the initialize event, which is
dispatched when the user first navigates to panel 2 of an Accordion container:
<?xml version="1.0"?>
<!-- containers\intro\AccordionInitEvent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
public function pane2_initialize():void {
Alert.show("Pane 2 has been created");
}
]]>
</mx:Script>
<mx:Accordion width="200" height="100">
<mx:VBox id="pane1" label="Pane 1">
<mx:Label text="This is pane 1"/>
</mx:VBox>
<mx:VBox id="pane2"
label="Pane 2"
initialize="pane2_initialize();">
<mx:Label text="This is pane 2"/>
</mx:VBox>
</mx:Accordion>
</mx:Application>
Disabling containers
All containers support the enabled property. By default, this property is set to true to enable
user interaction with the container and with the container’s children. If you set enabled to
false, Flex dims the color of the container and of all of its children, and blocks user input to
the container and to all of its children.
504
Introducing Containers
Using the Panel container
One container that you often use in a Flex application is the Panel container. The Panel
container consists of a title bar, a caption, a status message, a border, and a content area for its
children. Typically, you use a Panel container to wrap self-contained application modules. For
example, you can define several Panel containers in your application where one Panel
container holds a form, a second holds a shopping cart, and a third holds a shopping catalog.
The Flex RichTextEditor control is a Panel control that contains a TextArea control and a
ControlBar control that has editing controls.
The following image shows a Panel container with a Form container as its child:
Panel container
Form container
For more information on the Panel container, see “Panel layout container” on page 601.
You can also define a ControlBar control as part of a Panel container. A ControlBar control
defines an area at the lower edge of the Panel container, below any children in the Panel
container.
You can use the ControlBar container to hold components that might be shared by the other
children in the Panel container, or for controls that operate on the content of the Panel
container. For example, you can use the ControlBar container to display the subtotal of a
shopping cart, where the shopping cart is defined in the Panel container. For a product
catalog, the ControlBar container can hold the Flex controls to specify quantity and to add an
item to a shopping cart. For more information on the ControlBar container, see “ControlBar
layout container” on page 562.
Using containers
505
Defining a default button
You use the defaultButton property of a container to define a default Button control within
a container. Pressing the Enter key while focus is on any control activates the Button control
as if it was explicitly selected.
For example, a login form displays TextInput controls for a user name and password and a
submit Button control. Typically, the user types a user name, tabs to the password field, types
the password, and presses the Enter key to submit the login information without explicitly
selecting the Button control. To define this type of interaction, set the defaultButton
property of the Form control to the id of the submit Button control, as the following example
shows:
<?xml version="1.0"?>
<!-- containers\intro\ContainerDefaultB.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
public function submitLogin():void {
text1.text="You just tried to log in";
}
]]>
</mx:Script>
<mx:Panel title="Default Button Example">
<mx:Form defaultButton="{mySubmitBtn}">
<mx:FormItem label="Username">
<mx:TextInput id="username"
width="100"/>
</mx:FormItem>
<mx:FormItem label="Password">
<mx:TextInput id="password"
width="100"
displayAsPassword="true"/>
</mx:FormItem>
<mx:FormItem>
<mx:Button id="mySubmitBtn"
label="Login"
click="submitLogin();"/>
</mx:FormItem>
</mx:Form>
<mx:Text id="text1" width="150"/>
</mx:Panel>
</mx:Application>
506
Introducing Containers
N O TE
The Enter key has a special purpose in the ComboBox control. When the drop-down list
of a ComboBox control is open, pressing Enter selects the currently highlighted item in
the ComboBox control; it does not activate the default button. Also, when the cursor is in
a TextArea control, pressing Enter adds a newline; it does not activate the default button.
Using scroll bars
Flex containers support scroll bars, which let you display an object that is larger than the
available screen space or display more objects than fit in the current size of the container, as
the following image shows:
Image at full size
Image in an HBox container
In this example, you use an HBox container to let users scroll an image, rather than rendering
the complete image at its full size:
<?xml version="1.0"?>
<!-- containers\intro\HBoxScroll.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox width="75" height="75">
<mx:Image source="assets/logo.jpg"/>
</mx:HBox>
</mx:Application>
In this example, you explicitly set the size of the HBox container to 75 by 75 pixels, a size
smaller than the imported image. If you omit the sizing restrictions on the HBox container, it
attempts to use its default size, which is a size large enough to hold the image.
By default, Flex draws scroll bars only when the contents of a container are larger than that
container. To force the container to draw scroll bars, you can set the
horizontalScrollPolicy and verticalScrollPolicy properties to on.
Using scroll bars
507
The following example creates an HBox container with scroll bars even though the image
inside is large enough to display fully without them:
<?xml version="1.0"?>
<!-- containers\intro\HBoxScrollOn.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:HBox horizontalScrollPolicy="on" verticalScrollPolicy="on">
<mx:Image source="assets/logo.jpg"/>
</mx:HBox>
</mx:Application>
Using container scroll properties
The following container properties and styles control scroll bar appearance and behavior:
■
The horizontalScrollPolicy and verticalScrollPolicy properties control the
display of scroll bars. By default, both properties are set to auto, which configures Flex to
include scroll bars only when necessary. You can set these properties to on to configure
Flex to always include scroll bars, or set the properties to off to configure Flex to never
include scroll bars. In ActionScript, you can use constants in the ScrollPolicy class, such as
ScrollPolicy.ON, to represent these values.
■
The horizontalLineScrollSize and verticalLineScrollSize properties determine
how many pixels to scroll when the user selects the scroll bar arrows. The default value is 5
pixels.
■
The horizontalPageScrollSize and verticalPageScrollSize properties determine
how many pixels to scroll when the user selects the scroll bar track. The default value is 20
pixels.
N OT E
If the clipContent property is false, a container lets its child extend past its boundaries.
Therefore, no scroll bars are necessary, and Flex never displays them, even if you set
horizontalScrollPolicy and verticalScrollPolicy to on.
Scroll bar layout considerations
Your configuration of scroll bars can affect the layout of your application. For example, if you
set the horizontalScrollPolicy and verticalScrollPolicy properties to on, the
container always includes scroll bars, even if they are not necessary. Each scroll bar is 16 pixels
wide. Therefore, turning them on when they are not needed is similar to increasing the size of
the right and bottom padding of the container by 16 pixels.
508
Introducing Containers
If you keep the default values of auto for the horizontalScrollPolicy and
verticalScrollPolicy properties, Flex lays out the application just as if the properties are
set to off. That is, the scroll bars are not counted as part of the layout.
If you do not keep this behavior in mind, your application might have an inappropriate
appearance. For example, if you have an HBox container that is 30 pixels high and 100 pixels
wide and has two buttons that are each 22 pixels high and 40 pixels wide, the children are
contained fully inside the HBox container, and no scroll bars appear. However, if you add a
third button, the children exceed the width of the HBox container, and Flex adds a horizontal
scroll bar at the bottom of the container. The scroll bar is 16 pixels high, which reduces the
height of the content area of the container from 30 pixels to 14 pixels. This means that the
Button controls, which are 22 pixels high, are too tall for the HBox, and Flex, by default, adds
a vertical scroll bar.
Controlling scroll delay and interval
Scroll bars have two styles that affect how they scroll:
■
The repeatDelay style specifies the number of milliseconds to wait after the user selects a
scroll button before repeating scrolling.
■
The repeatInterval style specifies the number of milliseconds to wait between each
repeated scroll while the user keeps the scroll arrows selected.
These settings are styles of the scroll bar subcontrol, not of the container, and, therefore,
require a different treatment than properties such as horizontalScrollPolicy. The
following example sets the scroll policy consistently for all scroll bars in the application:
<?xml version="1.0"?>
<!-- containers\intro\HBoxScrollDelay.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Style>
HScrollBar, VScrollBar {
repeatDelay: 2000;
repeatInterval:1000;
}
</mx:Style>
<mx:HBox id="hb1" width="75" height="75">
<mx:Image source="adobe_logo.gif"/>
</mx:HBox>
</mx:Application>
Using scroll bars
509
This example results in the same scrollable logo as shown in “Using scroll bars” on page 507,
but the scroll bars behave differently. When the user clicks and holds the mouse button down
over any of the scroll bar arrows or the scroll bar track, the image initially scrolls once, waits
two seconds, and then scrolls at a rate of one line or page a second.
To set a style on a single scroll bar, use a line such as the following in the event listener for the
initialize event for the application or the control with the scroll bar:
ScrollBar(hb1.horizontalScrollBar).setStyle("repeatDelay", 2000);
In this case, hb1 is an HBox control. All containers have horizontalScrollBar and
verticalScrollBar properties that represent the container’s ScrollBar subcontrols, if they
exist. You must cast these properties to the ScrollBar class, because their type is the IScrollBar
interface, not the ScrollBar class.
Using Flex coordinates
Adobe Flash and Flex support three coordinate systems for different purposes:
■
global
■
local
■
content
The following sections describe the coordinate systems, when they are used, and when and
how to use Flex properties and methods to convert between coordinate systems.
About the coordinate systems
The following table describes the coordinate systems:
Coordinate Description
system
global
510
Coordinates are relative to the upper-left corner of the Stage in Adobe Flash
Player, that is, the outermost edge of the application.
The global coordinate system provides a universal set of coordinates that are
independent of the component context. Uses for this coordinate system
include determining distances between objects and as an intermediate point
in converting between coordinates relative to a subcontrol into coordinates
relative to a parent control.
The MouseEvent class includes stageX and stageY properties that are in the
global coordinate system.
Introducing Containers
Coordinate Description
system
local
Coordinates are relative to the upper-left corner of the component.
Flex uses the local coordinate system for mouse pointer locations; all
components have mouseX and mouseY properties that use the local coordinate
system.
The MouseEvent class includes localX and localY properties that are in the
local coordinate system. Also, the Drag Manager uses local coordinates in
drag-and-drop operations. The doDrag() method’s xOffset and yOffset
properties, for example, are offsets relative to the local coordinates.
content
Coordinates are relative to the upper-left corner of the component’s content.
Unlike the local and global coordinates, the content coordinates include all of
the component’s content area, including any regions that are currently clipped
and must be accessed by scrolling the component. Thus, if you scrolled down
a Canvas container by 100 pixels, the upper-left corner of the visible content
is at position 0, 100 in the content coordinates.
You use the content coordinate system to set and get the positions of children
of a container that uses absolute positioning. (For more information on
absolute positioning, see “About component positioning” on page 224.)
The UIComponent contentMouseX and contentMouseY properties report the
mouse pointer location in the content coordinate system.
The following image shows these coordinate systems and how they relate to each other.
contentPane bounds
content 0, 0
global 0, 0
local 0, 0
component bounds
stage bounds
Using Flex coordinates
511
Using coordinate properties and methods
In some cases, you have to convert positions between coordinate systems. Examples where you
convert between coordinates include the following:
■
The MouseEvent class has properties that provide the mouse position in the global
coordinate system and the local coordinates of the event target. You use the content
coordinates to specify the locations in a Canvas container, or Application or Panel
container that uses absolute positioning. To determine the location of the mouse event
within the Canvas container contents, not just the visible region, you must determine the
position in the content coordinate system.
■
Custom drag-and-drop handlers might have to convert between the local coordinate
system and the content coordinate system when determining an object-specific drag
action; for example, if you have a control with scroll bars and you want to know the drag
(mouse) location over the component contents. The example in “Example: Using the
mouse position in a Canvas container” on page 513 shows this use.
■
Custom layout containers, where you include both visual elements, such as scroll bars or
dividers, and content elements. For example, if you have a custom container that draws
lines between its children, you have to know where each child is in the container’s content
coordinates to draw the lines.
Often, you use mouse coordinates in event handlers; when you do, you should keep the
following considerations in mind:
■
When you handle mouse events, it is best to use the coordinates from the MouseEvent
object whenever possible, because they represent the mouse coordinates at the time the
event was generated. Although you can use the container’s contentMouseX and
contentMouseY properties to get the mouse pointer locations in the content coordinate
system, you should, instead, get the local coordinate values from the event object and
convert them to the content coordinate system.
■
When you use local coordinates that are reported in an event object, such as the
MouseEvent localX and localY properties, you must remember that the event
properties report the local coordinates of the mouse relative to the event target. The target
component can be a subcomponent of the component in which you determine the
position, such as a UITextField inside a Button component, not the component itself. In
such cases, you must convert the local coordinates into the global coordinate system first,
and then convert the global coordinates into the content coordinates container.
512
Introducing Containers
Coordinate conversion properties and methods
All Flex components provide two read-only properties and six functions that enable you to use
and convert between coordinate systems. The following table describes these properties and
functions:
Property or function
Description
contentMouseX
Returns the x position of the mouse, in the content coordinates
of the component.
contentMouseY
Returns the y position of the mouse, in the content coordinates
of the component.
contentToGlobal
(point:Point):Point
Converts a Point object with x and y coordinates from the
content coordinate system to the global coordinate system.
contentToLocal
(point:Point):Point
Converts a Point object from the content coordinate system to
the local coordinate system of the component.
globalToContent
(point:Point):Point
Converts a Point object from the global coordinate system to
the content coordinate system of the component.
globalToLocal
(point:Point):Point
Converts a Point object from the global coordinate system to
the local coordinate system of the component.
localToContent
(point:Point):Point
Converts a Point object from the local coordinate system to the
content coordinate system of the component.
localToGlobal
(point:Point):Point
Converts a Point object from the local coordinate system to the
global coordinate system.
Example: Using the mouse position in a Canvas
container
The following example shows the use of the localToGlobal() and globalToContent()
methods to determine the location of a mouse pointer within a Canvas container that
contains multiple child Canvas containers.
Using Flex coordinates
513
This example is somewhat artificial, in that production code would use the MouseEvent class
stageX and stageY properties, which represent the mouse position in the global coordinate
system. The example uses the localX and localY properties, instead, to show how you can
convert between local and content coordinates, including how first converting to using the
global coordinates ensures the correct coordinate frame of reference.
<?xml version="1.0"?>
<!-- containers\intro\MousePosition.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
backgroundColor="white">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
// Handle the mouseDown event generated
// by clicking in the application.
private function handleMouseDown(event:MouseEvent):void {
// Convert the mouse position to global coordinates.
// The localX and localY properties of the mouse event contain
// the coordinates at which the event occurred relative to the
// event target, typically one of the
// colored internal Canvas controls.
// A production version of this example could use the stageX
// and stageY properties, which use the global coordinates,
// and avoid this step.
// This example uses the localX and localY properties only to
// illustrate conversion between different frames of reference.
var pt:Point = new Point(event.localX, event.localY);
pt = event.target.localToGlobal(pt);
// Convert the global coordinates to the content coordinates
// inside the outer c1 Canvas control.
pt = c1.globalToContent(pt);
// Figure out which quadrant was clicked.
var whichColor:String = "border area";
if (pt.x < 150) {
if (pt.y < 150)
whichColor = "red";
else
whichColor = "blue";
}
else {
if (pt.y < 150)
whichColor = "green";
else
514
Introducing Containers
whichColor = "magenta";
}
Alert.show("You clicked on the " + whichColor);
}
]]>
</mx:Script>
<!-- Canvas container with four child Canvas containers -->
<mx:Canvas id="c1"
borderStyle="none"
width="300" height="300"
mouseDown="handleMouseDown(event);">
<mx:Canvas
width="150" height="150"
x="0" y="0"
backgroundColor="red">
<mx:Button label="I'm in Red"/>
</mx:Canvas>
<mx:Canvas
width="150" height="150"
x="150" y="0"
backgroundColor="green">
<mx:Button label="I'm in Green"/>
</mx:Canvas>
<mx:Canvas
width="150" height="150"
x="0" y="150"
backgroundColor="blue">
<mx:Button label="I'm in Blue"/>
</mx:Canvas>
<mx:Canvas
width="150" height="150"
x="150" y="150"
backgroundColor="magenta">
<mx:Button label="I'm in Magenta"/>
</mx:Canvas>
</mx:Canvas>
</mx:Application>
Using Flex coordinates
515
Creating and managing component
instances at run time
You typically use MXML to lay out the user interface of your application, and use
ActionScript for event handling and run-time control of the application. You can also use
ActionScript to create component instances at run time. For example, you could use MXML
to define an empty Accordion container and use ActionScript to add panels to the container
in response to user actions.
About the display list and container children
Flash Player maintains a tree of visible (or potentially visible) objects that make up your
application. The root of the tree is the Application object, and child containers and
components are branches and leaf nodes of the tree. That tree is known as the display list.
When you add child components to a container or remove child components from a
container, you are adding and removing them from the display list. You can also change their
relative positions by changing their positions in the display list.
Although the display list is a tree rooted at the top of the application, when you manipulate a
container’s children in ActionScript by using the container’s methods and properties, you only
access the container’s direct children, and you treat them as items in a list with an index that
starts at 0 for the container’s first child in the display list.
The Container class includes the numChildren property, which contains a count of the
number of direct child components that the container has in the display list. The following
HBox container, for example, includes two child components, so the value of its
numChildren property is 2:
<mx:HBox id="myContainer">
<mx:Button click="clickHandler();"/>
<mx:TextInput/>
</mx:HBox>
516
Introducing Containers
You can access and modify a container’s child components at run time by using the
addChild(), addChildAt(), getChildren(), getChildAt(), getChildByName(),
removeAllChildren(), removeChild(), and removeChildAt() methods of the Container
class. For example, you can iterate over all the child component of a container, as the
following example shows:
private function clickHandler():void {
var numChildren:Number = myContainer.numChildren;
for (var i:int = 0; i < numChildren; i++) {
trace(myContainer.getChildAt(i));
}
}
The Container class also defines the rawChildren property that contains the full display list
of all of the children of a container. This list includes all the container’s children, plus the
DisplayObjects that implement the container’s chrome (display elements), such as its border
and the background image. For more information see “Accessing display-only children”
on page 519.
Creating and managing component instances at run time
517
Obtaining the number of child components in a container or
application
To get the number of direct child components in a container, get the value of the container’s
numChildren property. The following application gets the number of children in the
application and a VBox container. The VBox control has five label controls, and therefore has
five children. The Application container has the VBox and Button controls as its children,
and therefore has two children.
<?xml version="1.0"?>
<!-- containers\intro\VBoxNumChildren.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
// Import the Alert class.
import mx.controls.Alert;
public function calculateChildren():void {
var myText:String = new String();
myText="The VBox container has " +
myVBox.numChildren + " children";
myText+="\nThe Application has " +
numChildren + " children";
Alert.show(myText);
}
]]>
</mx:Script>
<mx:VBox id="myVBox" borderStyle="solid">
<mx:Label text="This is label 1"/>
<mx:Label text="This is label 2"/>
<mx:Label text="This is label 3"/>
<mx:Label text="This is label 4"/>
<mx:Label text="This is label 5"/>
</mx:VBox>
<mx:Button label="Show Children" click="calculateChildren();"/>
</mx:Application>
In the main MXML application file, the file that contains the <mx:Application> tag, the
current scope is always the Application object. Therefore, the reference to the numChildren
property without an object prefix refers to the numChildren property of the Application
object. For more information on accessing the root application, see “About scope” on page 66.
518
Introducing Containers
Accessing display-only children
The numChildren property and getChildAt() method let you count and access only child
components. Also, the container may contain style elements and skins, such as the border and
background. The container’s rawChildren property lets you access all children of a container,
including the component “content children” and the skin and style “display children.” The
object returned by the rawChildren property implements the IChildList interface. You then
use methods and properties of this interface, such as getChildAt(), to access and manipulate
all the container’s children.
Creating and removing components at run time
To create a component instance at run time, you define it, set any properties, and then add it
as a child of a parent container by calling the addChild() method on the parent container.
This method has the following signature:
addChild(child:DisplayObject):DisplayObject
The child argument specifies the component to add to the container.
N OT E
Although the child argument of the method is specified as type DisplayObject, the
argument must implement the IUIComponent interface to be added as a child of a
container. All Flex components implement this interface.
For example, the following application creates an HBox container with a Button control
called myButton:
<?xml version="1.0"?>
<!-- containers\intro\ContainerAddChild.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.controls.Button;
public function addButton():void {
var myButton:Button = new Button();
myButton.label = "New Button";
myHBox.addChild(myButton);
}
]]>
</mx:Script>
<mx:HBox id="myHBox" initialize="addButton();"/>
</mx:Application>
Creating and managing component instances at run time
519
This example creates the control when the application is loaded rather than in response to any
user action. However, you could add a new button when the user presses an existing button,
as the following example shows:
<?xml version="1.0"?>
<!-- containers\intro\ContainerAddChild2.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
horizontalAlign="left">
<mx:Script>
<![CDATA[
import mx.controls.Button;
public function addButton():void {
var myButton:Button = new Button();
myButton.label = "New Button";
myHBox.addChild(myButton);
}
]]>
</mx:Script>
<mx:HBox id="myHBox">
<mx:Button label="Add Button" click="addButton();"/>
</mx:HBox>
</mx:Application>
The following image shows the resulting application after the user presses the original
(leftmost) button three times:
520
Introducing Containers
You use the removeChild() method to remove a control from a container. Flex sets the
parent property of the removed child. If the child is no longer referenced anywhere else in
your application after the call to the removeChild() method, it gets destroyed by a garbage
collection process. The following example removes a button from the application when the
user presses it:
<?xml version="1.0"?>
<!-- containers\intro\ContainerRemoveChild.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
public function removeButton():void {
myHBox.removeChild(myButton);
}
]]>
</mx:Script>
<mx:HBox id="myHBox">
<mx:Button id="myButton"
label="Remove Me"
click="removeButton();"/>
</mx:HBox>
</mx:Application>
For additional methods that you can use with container children, see the Container class in
Adobe Flex 2 Language Reference.
Creating and managing component instances at run time
521
Example: Creating and removing a child of an VBox container
The following example uses MXML to defines a VBox container that contains two Button
controls. You use one Button control to add a CheckBox control to the VBox container, and
one Button control to delete it.
<?xml version="1.0"?>
<!-- containers\intro\ContainerComponentsExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
// Import the CheckBox class.
import mx.controls.CheckBox;
// Define a variable to hold the new CheckBox control.
private var myCheckBox:CheckBox;
// Define a variable to track if the CheckBox control
// is in the display list.
private var checkBoxDisplayed:Boolean = false;
public function addCB():void {
// Make sure the check box isn't being displayed.
if(checkBoxDisplayed==false){
// Create the check box if it does not exist.
if (!myCheckBox) {
myCheckBox = new CheckBox();
}
// Add the check box.
myCheckBox.label = "New CheckBox";
myVBox.addChild(myCheckBox);
checkBoxDisplayed=true;
}
}
public function delCB():void {
// Make sure a CheckBox control exists.
if(checkBoxDisplayed){
myVBox.removeChild(myCheckBox);
checkBoxDisplayed=false;
}
}
]]>
</mx:Script>
<mx:VBox id="myVBox">
<mx:Button label="Add CheckBox"
522
Introducing Containers
click="addCB();"/>
<mx:Button label="Remove CheckBox"
click="delCB();"/>
</mx:VBox>
</mx:Application>
The following image shows the resulting application after the user presses the Add CheckBox
button:
Creating and managing component instances at run time
523
Example: Creating and removing children of an Accordion
container
The example in this section adds and removes panels to an Accordion container. The
Accordion container initially contains one panel. Each time you select the Add HBox button,
it adds a new HBox container to the Accordion container.
<?xml version="1.0"?>
<!-- containers\intro\ContainerComponentsExample2.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
// Import HBox class.
import mx.containers.HBox;
//Array of created containers
private var hBoxes:Array = [];
public function addHB():void {
// Create new HBox container.
var newHB:HBox = new HBox();
newHB.label="my label: " + String(hBoxes.length);
// Add it to the Accordion container, and to the
// Array of HBox containers.
hBoxes.push(myAcc.addChild(newHB));
}
public
//
//
if
function delHB():void {
If there is at least one HBox container in the Array,
remove it.
(hBoxes.length>= 1) {
myAcc.removeChild(hBoxes.pop());
}
}
]]>
</mx:Script>
<mx:VBox>
<mx:Accordion id="myAcc" height="150" width="150">
<mx:HBox label="Initial HBox"/>
</mx:Accordion>
<mx:Button label="Add HBox" click="addHB();"/>
<mx:Button label="Remove HBox" click="delHB();"/>
</mx:VBox>
</mx:Application>
524
Introducing Containers
Controlling child order
You can control the order of children by adding them in a specific order. You can also control
them as follows:
■
By using the addChildAt() method to specify where among the component’s children to
add a child
■
By using the setChildIndex() method to specify the location of a specific child among a
component’s children in the display list
N OT E
As with the addChild() method, although the child argument of the addChildAt()
method is specified as type DisplayObject, the argument must implement the
IUIComponent interface to be added as a child of a container. All Flex components
implement this interface.
Creating and managing component instances at run time
525
The following example modifies the example in “Example: Creating and removing a child of
an VBox container” on page 522. It uses the addChildAt() method to add the CheckBox
control as the first child (index 0) of the VBox. It also has a Reorder children button that uses
the setChildIndex() method to move a CheckBox control down the display list until it is
the last the child in the VBox container. Boldface text indicates the lines that are added to or
changed from the previous example.
<?xml version="1.0"?>
<!-- containers\intro\ContainerComponentsReorder.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
// Import the CheckBox and Alert classes.
import mx.controls.CheckBox;
import mx.controls.Alert;
// Define a variable to hold the new CheckBox control.
private var myCheckBox:CheckBox;
// Define a variable to track if the CheckBox control
// is in the display list.
private var checkBoxDisplayed:Boolean = false;
public function addCB():void {
// Make sure the check box isn't being displayed.
if(checkBoxDisplayed==false){
// Create the check box if it does not exist.
if (!myCheckBox) {
myCheckBox = new CheckBox();
}
// Add the check box as the first child of the VBox.
myCheckBox.label = "New CheckBox";
myVBox.addChildAt(myCheckBox, 0);
checkBoxDisplayed=true;
}
}
public function delCB():void {
// Make sure a CheckBox control exists.
if(checkBoxDisplayed){
myVBox.removeChild(myCheckBox);
checkBoxDisplayed=false;
}
}
public function reorder():void {
// Make sure a CheckBox control exists.
526
Introducing Containers
if(checkBoxDisplayed==true){
// Don't try to move the check box past the end
// of the children. Because indexes are 0 based,
// the last child index is one less
// than the number of children.
if (myVBox.getChildIndex(myCheckBox) < myVBox.numChildren-1)
{
// Increment the checkBoxIndex variable and use it to
// set the index of the check box among the VBox children.
myVBox.setChildIndex(myCheckBox,
myVBox.getChildIndex(myCheckBox) + 1);
}
}
else {
Alert.show("Add the check box before you can move it");
}
}
]]>
</mx:Script>
<mx:VBox id="myVBox">
<mx:Button label="Add CheckBox" click="addCB();"/>
<mx:Button label="Remove CheckBox" click="delCB();"/>
<mx:Button label="Reorder children" click="reorder();"/>
</mx:VBox>
</mx:Application>
Creating and managing component instances at run time
527
528
Introducing Containers
CHAPTER 14
14
Using the Application
Container
Adobe Flex defines a default Application container that lets you start adding content to your
application without having to explicitly define another container. This topic describes how to
use an Application container.
Flex defines any MXML file that contains an <mx:Application> tag as an Application
object. For more information, see “About the Application object” on page 537.
The Application container supports an application preloader that uses a progress bar to show
the download progress of an application SWF file. You can override the default progress bar to
define your own custom progress bar. For more information, see “Showing the download
progress of an application” on page 542.
Contents
Using the Application container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
About the Application object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
Showing the download progress of an application . . . . . . . . . . . . . . . . . . . . . . . . . . 542
Using the Application container
Flex defines an Application container that serves as the default container for any content that
you add to your application. Flex creates this container from the <mx:Application> tag,
which must be the first tag in an MXML application file. The Application object is the default
scope for any ActionScript code in the file, and the <mx:Application> tag defines the initial
size of the application.
Although you may find it convenient to use the Application container as the only container in
your application, usually you explicitly define at least one more container before you add any
controls to your application. Often, you use a Panel container as the first container after the
<mx:Application> tag.
529
The Application container has the following default layout characteristics:
Property
Default value
Default size
The size of the browser window
Child alignment
Vertical column arrangement of children
Child horizontal alignment Centered
Default padding
24 pixels for the top, bottom, left, and right properties
Sizing an Application container and its children
An Application container arranges its children in a single vertical column. You can set the
height and width of the Application container by using explicit pixel values or by using
percentage values, where the percentage values are relative to the size of the browser window.
By default, the Application container has a height and width of 100%, which means that it
fills the entire browser window.
The following example sets the size of the Application container to one-half of the width and
height of the browser window:
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
height="50%" width="50%">
...
</mx:Application>
The advantage of using percentages to specify the size is that Flex can resize your application
as the user resizes the browser window. Flex maintains the Application container size as a
percentage of the browser window as the user resizes it.
530
Using the Application Container
If you set the width and height properties of the child components MXML tags to
percentage values, your components can also resize as your application resizes, as the following
example shows:
<?xml version="1.0"?>
<!-- containers\application\AppSizePercent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
width="100%" height="100%">
<mx:Panel title="Main Application" width="100%" height="100%">
<mx:HDividedBox width="100%" height="100%">
<mx:TextArea width="50%" height="100%"/>
<mx:VDividedBox width="50%" height="100%">
<mx:DataGrid width="100%" height="25%"/>
<mx:TextArea width="100%" height="75%"/>
</mx:VDividedBox>
</mx:HDividedBox>
</mx:Panel>
</mx:Application>
The following example uses explicit pixel values to size the Application container:
<?xml version="1.0"?>
<!-- containers\application\AppSizePixel.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
height="100" width="150">
<mx:Panel title="Main Application">
<mx:TextInput id="mytext" text="Hello"/>
<mx:Button id="mybutton" label="Get Weather"/>
</mx:Panel>
</mx:Application>
If the children of the Application container are sized or positioned such that some or all of the
component is outside of the visible area of the Application container, Flex adds scroll bars to
the container, as the preceding example shows.
If you want to set a child container to fill the entire Application container, the easiest method
is to set the child’s MXML tag width and height properties to 100% (or, in ActionScript, set
the percentWidth and percentHeight properties to 100), and set the Application container
padding to 0. If you base the child container’s width and height properties on those of the
Application container, you must subtract the Application container’s padding, or your child
container will be larger than the available space, and the application will have scroll bars.
Using the Application container
531
In the following example, the VBox container expands to fill all the available space, except for
the area defined by the Application container padding:
<?xml version="1.0"?>
<!-- containers\application\AppVBoxSize.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
width="100" height="100">
<mx:VBox width="100%" height="100%" backgroundColor="#A9C0E7">
<!-- ... -->
</mx:VBox>
</mx:Application>
In the following example, the VBox container is larger than the available space within the
Application container, which results in scroll bars:
<?xml version="1.0"?>
<!-- containers\application\AppVBoxSizeScroll.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
width="100" height="100">
<mx:VBox width="200" height="200" backgroundColor="#A9C0E7">
<!-- ... -->
</mx:VBox>
</mx:Application>
In the following example, the Application container has no padding, which lets its child VBox
container fill the entire window:
<?xml version="1.0"?>
<!-- containers\application\AppNoPadding.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
width="100" height="100"
paddingTop="0" paddingBottom="0"
paddingLeft="0" paddingRight="0">
<mx:VBox width="100" height="100" backgroundColor="#A9C0E7">
<!-- ... -->
</mx:VBox>
</mx:Application>
532
Using the Application Container
Overriding the default Application container styles
By default, the Application container has the following default style properties that define the
following visual aspects of a Flex application and differ from the default container values:
Property
Default value
backgroundColor
The color of the Stage area of Adobe Flash Player, which is
visible during application loading and initialization. This color
is also visible if the application background is transparent. The
default value is 0x869CA7.
backgroundGradientAlphas
[1.0, 1.0], a fully opaque background.
backgroundGradientColors
[0x9CBOBA, 0x68808C], a grey background that is slightly
darker at the bottom.
backgroundImage
A gradient controlled by the backgroundGradientAlphas and
backgroundGradientColors styles. The default value is
mx.skins.halo.ApplicationBackground.
backgroundSize
100%. When you set this property at 100%, the background
image takes up the entire Application container.
horizontalAlign
Centered.
paddingBottom
24 pixels.
paddingLeft
24 pixels.
paddingRight
24 pixels.
paddingTop
24 pixels.
You can override these default values in your application to define your own default style
properties.
Changing the Application background
The Application container backgroundGradientAlphas, backgroundGradientColors, and
backgroundImage styles control the container background. By default, these properties
define an opaque grey gradient background.
You specify an image for the application background by using the backgroundImage
property. If you set both the backgroundImage property and the
backgroundGradientColors property, Flex ignores backgroundGradientColors.
Using the Application container
533
You can specify a gradient background for the application in two ways:
■
Set the backgroundGradientColors property to two values, as in the following example:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
backgroundGradientColors="[0x0000FF, 0xCCCCCC]">
Flex calculates the gradient pattern between the two specified values.
■
Set the backgroundColor property to the desired value, as in the following example:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
backgroundColor="red">
Flex calculates the gradient pattern between a color slightly darker than red, and a color
slightly lighter than red.
To set a solid background to the application, specify the same two values to the
backgroundGradientColors property, as the following example shows:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
backgroundGradientColors="[#FFFFFF, #FFFFFF]">
This example defines a solid white background.
The backgroundColor property specifies the background color of the Stage area in Flash
Player, which is visible during application loading and initialization, and a background
gradient while the application is running. By default, the backgroundColor property is set to
0x869CA7, which specifies a dark blue-grey color.
If you use the backgroundGradientColors property to set the application background, you
should also set the backgroundColor property to compliment the
backgroundGradientColors property, as the following example shows:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
backgroundGradientColors="[0x0000FF, 0xCCCCCC]"
backgroundColor="0x0000FF">
In this example, you use the backgroundGradientColors property to set a gradient pattern
from a dark blue to grey, and the backgroundColor property to set the Stage area in Flash
Player to dark blue, which will be visible during application loading and initialization.
Using the plain style
The Flex default style sheet defines a plain style name that sets all padding to 0 pixels, removes
the default background image, sets the background color to white, and left-aligns the
children. The following example shows how you can set this style:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
styleName="plain">
534
Using the Application Container
You can override individual values in the plain setting, as the following example shows:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
styleName="plain" horizontalAlign="center"/>
Overriding styles with the Style tag
You can also use the <mx:Style> tag in your application to specify alternative style values, as
the following example shows:
<?xml version="1.0"?>
<!-- containers\application\AppStyling.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<!-- Style definition for the entire application. -->
<mx:Style>
Application {
paddingLeft: 10px;
paddingRight: 10px;
paddingTop: 10px;
paddingBottom: 10px;
horizontalAlign: "left";
backgroundImage: "";
backgroundColor: #AAAACC;
}
</mx:Style>
<mx:Panel title="Main Application">
<mx:TextInput id="mytext" text="Hello"/>
<mx:Button id="mybutton" label="Get Weather"/>
</mx:Panel>
</mx:Application>
This example removes the background image, sets all padding to 10 pixels, left-aligns
children, and sets the background color to a light blue.
For more information on using styles, see Chapter 18, “Using Styles and Themes,” on
page 697.
Viewing the application source code
You can use the viewSourceURL property of the Application container to specify a URL to
the application’s source code. If you set this property, Flex adds a View Source menu item to
the application’s context menu, which you open by right-clicking anywhere in your
application. Select the View Source menu item to open the URL specified by the
viewSourceURL property in a new browser window.
Using the Application container
535
You must set the viewSourceURL property by using MXML, not ActionScript, as the
following example shows:
<?xml version="1.0"?>
<!-- containers\application\AppSourceURL.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
viewSourceURL="http://localhost:8100/flex/assets/AppSourceURL.txt">
<mx:Button/>
</mx:Application>
You typically deploy your source code not as an MXML file but as a text or HTML file. In
this example, the source code is in the file AppSourceURL.txt. If you use an HTML file to
represent your source code, you can add formatting and coloring to make it easier to read.
Specifying options of the Application container
You can specify several options of the <mx:Application> tag to control your application.
The following table describes these options:
Option
Type
frameRate
Number Specifies the frame rate of the application, in frames per
second. The default value is 24.
pageTitle
String
Specifies a String that appears in the title bar of the
browser. This property provides the same functionality as
the HTML <title> tag.
preloader
Path
Specifies the path of a SWC component class or
ActionScript component class that defines a custom
progress bar.
A SWC component must be in the same directory as the
MXML file or in the WEB-INF/flex/user_classes directory
of your Flex web application.
For more information, see “Showing the download
progress of an application” on page 542.
scriptRecursionLimit
Number Specifies the maximum depth of the Flash Player call
stack before Flash Player stops. This is essentially the
stack overflow limit.
The default value is 1000.
536
Using the Application Container
Description
Option
Type
Description
scriptTimeLimit
Number Specifies the maximum duration, in seconds, that an
ActionScript event listener can execute before Flash
Player assumes that it has stopped processing and aborts
it.
The default value is 60 seconds, which is also the
maximum allowable value that you can set.
usePreloader
Boolean Specifies whether to disable the application preloader
(false) or not (true). The default value is true. To use the
default preloader, your application must be at least 160
pixels wide.
For more information, see “Showing the download
progress of an application” on page 542.
About the Application object
Flex compiles your application into a SWF file that contains a single Application object,
defined by the <mx:Application> tag. In most cases, your Flex application has one
Application object. Some applications use the SWFLoader control to add more applications.
An Application object has the following characteristics:
■
Application objects are MXML files with an <mx:Application> tag.
■
Most Flex applications have a single Application object.
■
The Application file is the first file loaded.
■
An Application object is also a Document object, but a Document object is not always an
Application object. For more information on the Document object, see “About the
Document object” on page 537.
■
You can refer to the Application object as mx.core.Application.application from
anywhere in the Flex application.
■
If you load multiple nested applications by using the SWFLoader control, you can access
the scope of each higher application in the nesting hierarchy by using
parentApplication, parentApplication.parentApplication, and so on.
About the Document object
Flex creates a Document object for every MXML file used in a Flex application. For example,
you can have a document, which is also an Application object, and from there, use other
MXML files that define custom controls.
About the Application object
537
A Document object has the following characteristics:
■
All MXML files that a Flex application uses are Document objects, including the
Application object’s file.
■
Custom ActionScript component files are Document objects.
■
The Flex compiler cannot compile a SWF file from a file that does not contain an
<mx:Application> tag.
■
Documents usually consist of MXML custom controls that you use in your Flex
application.
■
You can access the scope of a document’s parent document by using parentDocument,
parentDocument.parentDocument, and so on.
■
Flex provides a UIComponent.isDocument property so that you can detect if any given
object is a Document object.
Accessing Document and Application object scopes
In your application’s main MXML file, the file that contains the <mx:Application> tag, you
can access the methods and properties of the Application object using the this keyword.
However, in custom ActionScript and MXML components, event listeners, or external
ActionScript class files, Flex executes in the context of those components and classes, and the
this keyword refers to the current Document object and not the Application object. You
cannot refer to a control or method in the application from one of these child documents
without specifying the location of the parent document.
Flex provides the following properties that you can use to access parent documents:
mx.core.Application.application
The top-level Application object, regardless of where in
the document tree your object executes.
mx.core.UIComponent.parentDocument
The parent document of the current document.
You can use parentDocument.parentDocument to walk up the tree of multiple documents.
mx.core.UIComponent.parentApplication
The Application object in which the current
object exists. Flex applications can load applications into applications, therefore, you can
access the immediate parent application by using this property. You can use
parentApplication.parentApplication to walk up the tree of multiple applications.
The following sections describe how to use these properties.
538
Using the Application Container
Using the mx.core.Application.application property
To access properties and methods of the top-level Application object from anywhere in your
application, you can use the application property of the Application class. For example, you
define an application that contains the doSomething() method, as the following code shows:
<?xml version="1.0"?>
<!-- containers\application\AppDoSomething.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:MyComps="myComponents.*">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
// Open an Alert control.
public function doSomething():void {
Alert.show("doSomething() called.");
}
]]>
</mx:Script>
<!-- Include the ButtonMXML.mxml component. -->
<MyComps:ButtonMXML/>
</mx:Application>
You can then use the Application.application property in the ButtonMXML.mxml
component to reference the doSomething() method, as the following example shows:
<?xml version="1.0"?>
<!-- containers\application\myComponents\ButtonMXML.mxml -->
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
// To refer to the members of the Application class,
// you must import mx.core.Application.
import mx.core.Application;
]]>
</mx:Script>
<mx:Button label="MXML Button"
click="Application.application.doSomething();"/>
</mx:HBox>
The application property is especially useful in applications that have one or more custom
MXML or ActionScript components that each use a shared set of data. At the application
level, you often store shared information and provide utility functions that any of the
components can access.
About the Application object
539
For example, suppose that you store the user’s name at the application level and implement a
utility function, getSalutation(), which returns the string “Hi, userName”. The following
example MyApplication.mxml file shows the application source that defines the
getSalutation() method:
<?xml version="1.0"?>
<!-- containers\application\AppSalutation.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:MyComps="myComponents.*">
<mx:Script>
<![CDATA[
public var userName:String="SMG";
public function getSalutation():String {
return "Hi, " + userName;
}
]]>
</mx:Script>
<!-- Include the ButtonGetSalutation.mxml component. -->
<MyComps:ButtonGetSalutation/>
</mx:Application>
To access the userName and call the getSalutation() method in your MXML components,
you can use the application property, as the following example from the
MyComponent.mxml component shows:
<?xml version="1.0"?>
<!-- containers\application\myComponents\ButtonGetSalutation.mxml -->
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"
width="100%" height="100%" >
<mx:Script>
<![CDATA[
// To refer to the members of the Application class,
// you must import mx.core.Application.
import mx.core.Application;
]]>
</mx:Script>
<mx:Label id="myL"/>
<mx:Button
click="myL.text=Application.application.getSalutation();"/>
</mx:VBox>
In this example, clicking the Button control executes the getSalutation() function to
populate the Label control.
540
Using the Application Container
Using the parentDocument property
To access the parent document of an object, you can use the parentDocument property. The
parent document is the object that contains the current object. All classes that inherit from
the UIComponent class have a parentDocument property.
In the following example, the application references the custom AccChildObject.mxml
component:
<?xml version="1.0"?>
<!-- containers\application\AppParentDocument.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:MyComps="myComponents.*">
<!-- Include the AccChildObject.mxml component. -->
<MyComps:AccChildObject/>
</mx:Application>
In this example, the application is the parent document of the AccChildObject.mxml
component. The following code from the AccChildObject.mxml component uses the
parentDocument property to define an Accordion container that is slightly smaller than the
Application container:
<?xml version="1.0"?>
<!-- containers\application\myComponents\AccChildObject.mxml -->
<mx:Accordion xmlns:mx="http://www.adobe.com/2006/mxml"
width="{parentDocument.width*.80}"
height="{parentDocument.height*.50}">
<mx:HBox/>
</mx:Accordion>
You use the parentDocument property in MXML scripts to go up a level in the chain of
parent documents. You can use the parentDocument to walk this chain by using multiple
parentDocument properties, as the following example shows:
parentDocument.parentDocument.doSomething();
The parentDocument property of the Application object is a reference to the application.
The parentDocument is typed as Object so that you can access properties and methods on
ancestor Document objects without casting.
Every UIComponent class has an isDocument property that is set to true if that
UIComponent class is a Document object, and false if it is not.
If a UIComponent class is a Document object, it has a documentDescriptor property. This
is a reference to the descriptor at the top of the generated descriptor tree in the generated
Document class.
About the Application object
541
For example, suppose that AddressForm.mxml component creates a subclass of the Form
container to define an address form, and the MyApp.mxml component creates two instances
of it: <AddressForm id="shipping"> and <AddressForm id="billing">.
In this example, the shipping object is a Document object. Its documentDescriptor property
corresponds to the <mx:Form> tag at the top of the AddressForm.mxml file (the definition of
the component), while its descriptor corresponds to the <AddressForm id="shipping"> tag
in MyApp.mxml file (an instance of the component).
Walking the document chain by using the parentDocument property is similar to walking the
application chain by using the parentApplication property.
Using the parentApplication property
Applications can load other applications; therefore, you can have a hierarchy of applications,
similar to the hierarchy of documents within each application. Every UIComponent class has
a parentApplication read-only property that references the Application object in which the
object exists. The parentApplication property of an Application object is never itself; it is
either the Application object into which it was loaded, or it is null (for the Application
object).
Walking the application chain by using the parentApplication property is similar to
walking the document chain by using the parentDocument property.
Showing the download progress of an
application
The Application class supports an application preloader that uses a download progress bar to
show the download progress of an application SWF file. By default, the application preloader
is enabled. The preloader keeps track of how many bytes have been downloaded and
continually updates the progress bar.
The download progress bar displays information about two different phases of the
application: the download phase and the initialization phase. The
Application.creationComplete event dismisses the preloader.
The following example shows the download progress bar during the initialization phase:
542
Using the Application Container
The download progress bar is not displayed if the SWF file is on your local host or if it is
already cached. If the SWF file is not on your local host and is not cached, the progress bar is
displayed if less than half of the application is downloaded after 700 milliseconds of
downloading.
Disabling the download progress bar
To disable the download progress bar, you set the usePreloader property of the Application
container to false, as the following example shows:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
usePreloader="false">
Creating a custom progress bar
By default, the application preloader uses the DownloadProgressBar class in the mx.preloaders
package to display the download progress bar. To create a custom download progress bar, you
can either create a subclass of the DownloadProgressBar class, or create a subclass of the
flash.display.Sprite class that implements the mx.preloaders.IPreloaderDsiplay interface.
You can implement a download progress bar component as a SWC component or an
ActionScript component. A custom download progress bar component that extends the Sprite
class should not use any of the standard Flex components because it would load too slowly to
be effective. Do not implement a download progress bar as an MXML component because it
also would load too slowly.
To use a custom download progress bar class, you set the preloader property of the
Application container to the path of a SWC component class or ActionScript component
class. A SWC component must be in the same directory as the MXML file or in a directory on
the classpath of your Flex application. An ActionScript component can be in one of those
directories or in a subdirectory of one of those directories. When a class is in a subdirectory,
you specify the subdirectory location as the package name in the preloader value; otherwise,
you specify the class name.
The code in the following example specifies a custom download progress bar called
CustomBar that is located in the mycomponents/mybars directory below the application’s
root directory:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
preloader="mycomponents.mybars.CustomBar">
Showing the download progress of an application
543
Download progress bar events
The operation of the download progress bar is defined by a set of events. These events are
dispatched by the Preloader class. A custom download progress bar must handle these events.
The following table describes the download progress bar events:
Event
Description
ProgressEvent.PROGRESS
Dispatched when the application SWF file is being downloaded.
The first PROGRESS event signifies the beginning of the download
process.
Event.COMPLETE
Dispatched when the SWF file has finished downloading. Either
zero or one COMPLETE event is dispatched.
FlexEvent.INIT_COMPLETE
Dispatched when the Flex application finishes initialization. This
event is always dispatched once, and is the last event that the
Preloader dispatches.
The download progress bar must dispatch a COMPLETE event
after it has received an INIT_COMPLETE event. The COMPLETE event
informs the Preloader that the download progress bar has
completed all operations and can be dismissed.
The download progress bar can perform additional tasks, such
as playing an animation, after receiving an INIT_COMPLETE event,
and before dispatching the COMPLETE event. Dispatching the
COMPLETE event should be the last action of the download
progress bar.
FlexEvent.INIT_PROGRESS
Dispatched when the Flex application completes an initialization
phase, as defined by calls to the measure(), commitProperties(),
or updateDisplayList() methods. This event describes the
progress of the application in the initialization phase.
RslEvent.RSL_ERROR
Dispatched when a Runtime Shared Library (RSL) fails to load.
RslEvent.RSL_LOADED
Dispatched when an RSL finishes loading. The total bytes and
total loaded bytes are included in the event object. This event is
dispatched for every RSL that is successfully loaded.
RSLEvent.RSL_PROGRESS
Dispatched when an RSL is being downloaded. The first
progress event signifies the beginning of the RSL download.
The event object for this event is of type RSLEvent.
The DownloadProgressBar class defines an event listener for all of these events. Within your
override of the DownloadProgressBar class, you can optionally override the default behavior
of the event listener. If you create a custom download progress bar as a subclass of the Sprite
class, you must define an event listener for each of these events.
544
Using the Application Container
Creating a simple subclass of the
DownloadProgressBar class
The easiest way to create your own download progress bar is to create a subclass of the
mx.preloaders.DownloadProgressBar class, and then modify it for your application
requirements.
Your example might define custom strings for the download progress bar, or set the minimum
time that it appears, as the following example shows:
package myComponents
{
import mx.preloaders.*;
import flash.events.ProgressEvent;
public class DownloadProgressBarSubClassMin extends DownloadProgressBar
{
public function DownloadProgressBarSubClassMin()
{
super();
// Set the download label.
downloadingLabel="Downloading app..."
// Set the initialization label.
initializingLabel="Initializing app..."
// Set the minimum display time to 2 seconds.
MINIMUM_DISPLAY_TIME=2000;
}
// Override to return true so progress bar appears
// during initialization.
override protected function showDisplayForInit(elapsedTime:int,
count:int):Boolean {
return true;
}
// Override to return true so progress bar appears during download.
override protected function showDisplayForDownloading(
elapsedTime:int, event:ProgressEvent):Boolean {
return true;
}
}
}
Showing the download progress of an application
545
You can use your custom class in a Flex application, as the following example shows:
<?xml version="1.0"?>
<!-- containers\application\MainDPBMin.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
preloader="myComponents.DownloadProgressBarSubClassMin">
<mx:Button/>
<mx:TextInput text="sub class min" />
</mx:Application>
546
Using the Application Container
Creating a subclass of the DownloadProgressBar
class
In the following example, you create a subclass of the DownloadProgressBar class to display
text messages that describe the status of the downloading and initialization of the application.
This example defines event listeners for the events dispatched by the download progress bar to
write the messages to flash.text.TextField objects.
package myComponents
{
import
import
import
import
import
import
flash.display.*;
flash.text.*;
flash.utils.*;
flash.events.*;
mx.preloaders.*;
mx.events.*;
public class MyDownloadProgressBar extends DownloadProgressBar
{
// Define a TextField control for text messages
// describing the download progress of the application.
private var progressText:TextField;
// Define a TextField control for the final text message.
// after the application initializes.
private var msgText:TextField;
public function MyDownloadProgressBar()
{
super();
// Configure the TextField for progress messages.
progressText = new TextField();
progressText.x = 10;
progressText.y = 90;
progressText.width = 400;
progressText.height = 400;
addChild(progressText);
// Configure the TextField for the final message.
msgText = new TextField();
msgText.x = 10;
msgText.y = 10;
msgText.width = 400;
msgText.height = 75;
addChild(msgText);
Showing the download progress of an application
547
}
// Define the event listeners for the preloader events.
override public function set preloader(preloader:Sprite):void {
// Listen for the relevant events
preloader.addEventListener(
ProgressEvent.PROGRESS, myHandleProgress);
preloader.addEventListener(
Event.COMPLETE, myHandleComplete);
preloader.addEventListener(
FlexEvent.INIT_PROGRESS, myHandleInitProgress);
preloader.addEventListener(
FlexEvent.INIT_COMPLETE, myHandleInitEnd);
}
// Event listeners for the ProgressEvent.PROGRESS event.
private function myHandleProgress(event:ProgressEvent):void {
progressText.appendText("\n" + "Progress l: " +
event.bytesLoaded + " t: " + event.bytesTotal);
}
// Event listeners for the Event.COMPLETE event.
private function myHandleComplete(event:Event):void {
progressText.appendText("\n" + "Completed");
}
// Event listeners for the FlexEvent.INIT_PROGRESS event.
private function myHandleInitProgress(event:Event):void {
progressText.appendText("\n" + "App Init Start");
}
// Event listeners for the FlexEvent.INIT_COMPLETE event.
private function myHandleInitEnd(event:Event):void {
msgText.appendText("\n" + "App Init End");
var timer:Timer = new Timer(2000,1);
timer.addEventListener(TimerEvent.TIMER, dispatchComplete);
timer.start();
}
// Event listener for the Timer to pause long enough to
// read the text in the download progress bar.
private function dispatchComplete(event:TimerEvent):void {
dispatchEvent(new Event(Event.COMPLETE));
}
}
}
548
Using the Application Container
You can use your custom class in a Flex application, as the following example shows:
<?xml version="1.0"?>
<!-- containers\application\MainDPB.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
preloader="myComponents.MyDownloadProgressBar">
<mx:Button/>
<mx:TextInput/>
</mx:Application>
Creating a subclass of Sprite
You can define a custom download progress bar as a subclass of the Sprite class. By
implementing your download progress bar as a subclass of Sprite, you can create a completely
custom look and feel to it, rather than overriding the behavior built into the
DownloadProgressBar class.
One common use for this type of download progress bar is to have it display a SWF file
during application initialization. For example, you could display a SWF file that shows a
running clock, or other type of image.
Showing the download progress of an application
549
The example in this section display a SWF file as the download progress bar. This class must
implement the IPreloaderDisplay interface.
package myComponents
{
import flash.display.*;
import flash.utils.*;
import flash.events.*;
import flash.net.*;
import mx.preloaders.*;
import mx.events.*;
public class MyDownloadProgressBarSWF extends Sprite
implements IPreloaderDisplay
{
// Define a Loader control to load the SWF file.
private var dpbImageControl:flash.display.Loader;
public function MyDownloadProgressBarSWF() {
super();
}
// Specify the event listeners.
public function set preloader(preloader:Sprite):void {
// Listen for the relevant events
preloader.addEventListener(
ProgressEvent.PROGRESS, handleProgress);
preloader.addEventListener(
Event.COMPLETE, handleComplete);
preloader.addEventListener(
FlexEvent.INIT_PROGRESS, handleInitProgress);
preloader.addEventListener(
FlexEvent.INIT_COMPLETE, handleInitComplete);
}
// Initialize the Loader control in the override
// of IPreloaderDisplay.initialize().
public function initialize():void {
dpbImageControl = new flash.display.Loader();
dpbImageControl.contentLoaderInfo.addEventListener(
Event.COMPLETE, loader_completeHandler);
dpbImageControl.load(new URLRequest("assets/dpbSWF.swf"));
}
// After the SWF file loads, set the size of the Loader control.
private function loader_completeHandler(event:Event):void
{
addChild(dpbImageControl);
dpbImageControl.width = 50;
550
Using the Application Container
dpbImageControl.height= 50;
dpbImageControl.x = 100;
dpbImageControl.y = 100;
}
// Define empty event listeners.
private function handleProgress(event:ProgressEvent):void {
}
private function handleComplete(event:Event):void {
}
private function handleInitProgress(event:Event):void {
}
private function handleInitComplete(event:Event):void {
var timer:Timer = new Timer(2000,1);
timer.addEventListener(TimerEvent.TIMER, dispatchComplete);
timer.start();
}
private function dispatchComplete(event:TimerEvent):void {
dispatchEvent(new Event(Event.COMPLETE));
}
// Implement IPreloaderDisplay interface
public function get backgroundColor():uint {
return 0;
}
public function set backgroundColor(value:uint):void {
}
public function get backgroundAlpha():Number {
return 0;
}
public function set backgroundAlpha(value:Number):void {
}
public function get backgroundImage():Object {
return undefined;
}
public function set backgroundImage(value:Object):void {
}
public function get backgroundSize():String {
return "";
Showing the download progress of an application
551
}
public function set backgroundSize(value:String):void {
}
public function get stageWidth():Number {
return 200;
}
public function set stageWidth(value:Number):void {
}
public function get stageHeight():Number {
return 200;
}
public function set stageHeight(value:Number):void {
}
}
}
552
Using the Application Container
15
CHAPTER 15
Using Layout Containers
In Adobe Flex, layout containers provide a hierarchical structure to arrange and configure the
components, such as Button and ComboBox controls, of a Flex application.
This topic describes the layout containers and their usage, and includes descriptions and
examples of all Flex layout containers. For detailed information on how Flex lays out
containers and their children, see Chapter 8, “Sizing and Positioning Components,” on
page 221.
Contents
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
553
About layout containers
A layout container defines a rectangular region of the Adobe Flash Player drawing surface and
controls the sizing and positioning of the child controls and child containers defined within
it. For example, a Form layout container sizes and positions its children in a layout similar to
an HTML form.
To use a layout container, you create the container, and then add the components that define
your application.
Flex provides the following layout containers:
■
Canvas layout container
■
Box, HBox, and VBox layout containers
■
ControlBar layout container
■
ApplicationControlBar layout container
■
DividedBox, HDividedBox, and VDividedBox layout containers
■
Form, FormHeading, and FormItem layout containers
■
Grid layout container
■
Panel layout container
■
Tile layout container
■
TitleWindow layout container
The following sections describe how to use each of the Flex layout containers.
Canvas layout container
A Canvas layout container defines a rectangular region in which you place child containers
and controls. Unlike all other components, you cannot let Flex lay child controls out
automatically. You must use absolute or constraint-based layout to position child components.
With absolute layout you specify the x and y positions of the children; with constraint-based
layout you specify side or center anchors. For detailed information on using these layout
techniques, see Chapter 8, “Sizing and Positioning Components,” on page 221.
The Canvas container has the following default sizing characteristics:
Property
Default value
Default size
Large enough to hold all its children at the default sizes of the children
Default padding
0 pixels for the top, bottom, left, and right values
For complete reference information, see Canvas in Adobe Flex 2 Language Reference.
554
Using Layout Containers
Creating and using a Canvas control
You define a canvas control in MXML using the <mx:Canvas> 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.
Creating a Canvas Control by using absolute positioning
You can use the x and y properties of each child to specify the child’s location in the Canvas
container. These properties specify the x and y coordinates of a child relative to the upper-left
corner of the Canvas container, where the upper-left corner is at coordinates (0,0). Values for
the x and y coordinates can be positive or negative integers. You can use negative values to
place a child outside 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 shows a Canvas container with three LinkButton controls and three
Image controls:
Canvas layout container
555
The following MXML code creates this Canvas container:
<?xml version="1.0"?>
<!-- containers\layouts\CanvasSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Canvas id="myCanvas"
height="200" width="200"
borderStyle="solid"
backgroundColor="white">
<mx:LinkButton label="Search"
x="10" y="30"
click="navigateToURL(new URLRequest('http://mycomp.com/search'))"/>
<mx:Image
height="50" width="50"
x="100" y="10"
source="@Embed(source='assets/search.jpg')"
click="navigateToURL(new URLRequest('http://mycomp.com/search'))"/>
<mx:LinkButton label="Help"
x="10" y="100"
click="navigateToURL(new URLRequest('http://mycomp.com/help'))"/>
<mx:Image
height="50" width="50"
x="100" y="75"
source="@Embed(source='assets/help.jpg')"
click="navigateToURL(new URLRequest('http://mycomp.com/help'))"/>
<mx:LinkButton label="Complaints"
x="10" y="170"
click="navigateToURL(
new URLRequest('http://mycomp.com/complain'))"/>
<mx:Image
height="50" width="50"
x="100" y="140"
source="@Embed(source='assets/complaint.jpg')"
click="navigateToURL(
new URLRequest('http://mycomp.com/complaint'))"/>
</mx:Canvas>
</mx:Application>
556
Using Layout Containers
Creating a Canvas container by using constraint-based layout
You can also use constraint-based layout to anchor any combination of the top, left, right, and
bottom sides of a child a specific distance from the Canvas edges, or to anchor the horizontal
or vertical center of the child a specific (positive or negative) pixel distance from the Canvas
center. To specify a constraint-based layout you use the top, bottom, left, right,
horizontalCenter, and verticalCenter styles. When you anchor the top and bottom, or
the left and right sides of the child container to the Canvas sides, if the Canvas control resizes,
the children also resize. The following example uses constraint-based layout to position an
HBox horizontally, and uses absolute values to specify the vertical width and position:
<?xml version="1.0"?>
<!-- containers\layouts\CanvasConstraint.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Canvas
width="150" height="150"
backgroundColor="#FFFFFF">
<mx:HBox id="hBox2"
left="30"
right="30"
y="50"
height="50"
backgroundColor="#A9C0E7">
</mx:HBox>
</mx:Canvas>
</mx:Application>
The example produces the following image:
Preventing overlapping children
When you use a Canvas container, some of your components may overlap, because the
Canvas container ignores its children’s sizes when it positions them. Similarly, children
components may overlap any borders or padding, because the Canvas container does not
adjust the coordinate system to account for them.
Canvas layout container
557
In the following example, the size and position of each component is carefully calculated to
ensure that none of the components overlap:
<?xml version="1.0"?>
<!-- containers\layouts\CanvasOverlap.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
width="100" height="100"
backgroundGradientColors="[0xFFFFFF, 0xFFFFFF]">
<mx:Canvas id="chboard" backgroundColor="#FFFFFF">
<mx:Image source="assets\BlackBox.jpg"
width="10" height="10" x="0" y="0"/>
<mx:Image source="assets\BlackBox.jpg"
width="10" height="10" x="20" y="0"/>
<mx:Image source="assets\BlackBox.jpg"
width="10" height="10" x="40" y="0"/>
<mx:Image source="assets\BlackBox.jpg"
width="10" height="10" x="10" y="10"/>
<mx:Image source="assets\BlackBox.jpg"
width="10" height="10" x="30" y="10"/>
<mx:Image source="assets\BlackBox.jpg"
width="10" height="10" x="0" y="20"/>
<mx:Image source="assets\BlackBox.jpg"
width="10" height="10" x="20" y="20"/>
<mx:Image source="assets\BlackBox.jpg"
width="10" height="10" x="40" y="20"/>
<mx:Image source="assets\BlackBox.jpg"
width="10" height="10" x="10" y="30"/>
<mx:Image source="assets\BlackBox.jpg"
width="10" height="10" x="30" y="30"/>
<mx:Image source="assets\BlackBox.jpg"
width="10" height="10" x="0" y="40"/>
<mx:Image source="assets\BlackBox.jpg"
width="10" height="10" x="20" y="40"/>
<mx:Image source="assets\BlackBox.jpg"
width="10" height="10" x="40" y="40"/>
</mx:Canvas>
</mx:Application>
This example produces the following image:
558
Using Layout Containers
If you set the width and height properties of one of the images to 20 pixels but don’t change
the positions accordingly, that image overlaps other images in the checkerboard. For example,
if you replace the seventh <mx:Image> tag in the preceding example with the following line,
the resulting image looks like the following image:
<mx:Image source="BlackBox.jpg" width="10" height="10" x="20" y="20"/>
Repositioning children at run time
You can build logic into your application to reposition a child of a Canvas container at run
time. For example, in response to a button click, the following code repositions an input text
box that has the id value text1 to the position x=110, y=110:
<?xml version="1.0"?>
<!-- containers\layouts\CanvasOverlap.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Canvas
width="300" height="300"
backgroundColor="#FFFFFF">
<mx:TextInput id="text1"
text="Move me"
x="50" y="50"/>
<mx:Button id="button1"
label="Move text1"
x="50" y="200"
click="text1.x=110; text1.y=110;"/>
</mx:Canvas>
</mx:Application>
Box, HBox, and VBox layout containers
The Box layout container lays out its children in a single vertical column or a single horizontal
row. You use the direction property of a Box container to determine either vertical (default)
or horizontal layout. The HBox and VBox containers are Box containers with horizontal
and vertical direction property values.
NO TE
To lay out children in multiple rows or columns, use a Tile or Grid container. For more
information, see “Tile layout container” on page 606 and “Grid layout container”
on page 594.
Box, HBox, and VBox layout containers
559
The following example shows one Box container with a horizontal layout and one with a
vertical layout:
Box container with horizontal layout
Box container with vertical layout (default)
A Box container has the following default sizing characteristics:
Property
Default value
Default size
Vertical Box The height is large enough to hold all its children at the
default or explicit height of the children, plus any vertical gap between the
children, plus the top and bottom padding of the container.
The width is the default or explicit width of the widest child, plus the left
and right padding of the container.
Horizontal Box The height is the default or explicit height of the tallest
child, plus the top and bottom padding for the container.
The width is large enough to hold all of its children at the default width of
the children, plus any horizontal gap between the children, plus the left
and right padding of the container.
Default padding
0 pixels for the top, bottom, left, and right values.
For complete reference information, see Box, HBox, and VBox in Adobe Flex 2 Language
Reference.
Creating a Box, HBox, or VBox container
You use the <mx:Box>, <mx:VBox>, and <mx:HBox> tags to define Box containers. Use the
VBox (vertical box) and HBox (horizontal box) containers as shortcuts so you do not have to
specify the direction property in the Box container. 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.
560
Using Layout Containers
The following example creates a Box container with a vertical layout:
<?xml version="1.0"?>
<!-- containers\layouts\BoxSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Box direction="vertical"
borderStyle="solid"
paddingTop="10"
paddingBottom="10"
paddingLeft="10"
paddingRight="10">
<mx:Button id="fname" label="Button 1"/>
<mx:Button id="lname" label="Button 2"/>
<mx:Button id="addr1" label="Button 3"/>
<mx:ComboBox id="state"/>
</mx:Box>
</mx:Application>
The following code example is equivalent to the previous example, except that this example
defines a vertical Box container by using the <mx:VBox> tag:
<?xml version="1.0"?>
<!-- containers\layouts\VBoxSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:VBox borderStyle="solid"
paddingTop="10"
paddingBottom="10"
paddingLeft="10"
paddingRight="10">
<mx:Button id="fname" label="Button 1"/>
<mx:Button id="lname" label="Button 2"/>
<mx:Button id="addr1" label="Button 3"/>
<mx:ComboBox id="state"/>
</mx:VBox>
</mx:Application>
Box, HBox, and VBox layout containers
561
ControlBar layout container
You use the ControlBar container with a Panel or TitleWindow container to hold
components that can be shared by the other children in the Panel or TitleWindow container.
For a product catalog, the ControlBar container can hold the Flex controls to specify quantity
and to add an item to a shopping cart, as the following example shows:
Panel container
ControlBar container
A ControlBar container has the following default sizing characteristics:
Property
Default value
Default size
The height is the default or explicit height of the tallest child, plus the top
and bottom padding of the container.
The width is large enough to hold all of its children at the default or
explicit width of the children, plus any horizontal gap between the
children, plus the left and right padding of the container.
Default padding
10 pixels for the top, bottom, left, and right values.
For complete reference information, see ControlBar in Adobe Flex 2 Language Reference.
562
Using Layout Containers
Creating a ControlBar container
You use the <mx:ControlBar> tag to define a ControlBar control in MXML. Specify an id
value if you intend to refer to a component elsewhere in your MXML code, either in another
tag or in an ActionScript block. You specify the <mx:ControlBar> tag as the last child tag of
an <mx:Panel> tag, as the following example shows:
<?xml version="1.0"?>
<!-- containers\layouts\CBarSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
private function addToCart():void {
// Handle event.
}
]]>
</mx:Script>
<mx:Panel title="My Application"
paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10">
<mx:HBox width="250" height="200">
<!-- Area for your catalog. -->
</mx:HBox>
<mx:ControlBar width="250">
<mx:Label text="Quantity"/>
<mx:NumericStepper/>
<!-- Use Spacer to push Button control to the right. -->
<mx:Spacer width="100%"/>
<mx:Button label="Add to Cart"
click="addToCart();"/>
</mx:ControlBar>
</mx:Panel>
</mx:Application>
ControlBar layout container
563
ApplicationControlBar layout container
You use the ApplicationControlBar container to hold components that provide access to
application navigation elements and commands. An ApplicationControlBar container for an
editor, for example, could include Button controls for setting the font weight, a ComboBox to
select the font, and a MenuBar control to select the edit mode. The ApplicationControlBar is
a sublcass of the ControlBar class; however, it has a different look and feel.
Typically, you place an ApplicationControlBar container at the top of the application, as the
following example shows:
If you dock the ApplicationControlBar container at the top of an application, it does not
scroll with the application contents.
The ApplicationControlBar container has the following default sizing characteristics:
Property
Default value
Default size
The height is the default or explicit height of the tallest child, plus the top
and bottom padding of the container.
In normal mode, the width is large enough to hold all of its children at the
default or explicit width of the children, plus any horizontal gap between
the children, plus the left and right padding of the container. In docked
mode, the width equals the application width.
If the application is not wide enough to contain all the controls in the
ApplicationControlBar container, the bar is clipped.
Default padding
5 pixels for the top value.
4 pixels for the bottom value.
8 pixels for the left and right values.
For complete reference information, see ApplicationControlBar in Adobe Flex 2 Language
Reference.
564
Using Layout Containers
Creating an ApplicationControlBar container
You use the <mx:ApplicationControlBar> tag to define a ControlBar control in MXML.
Specify an id value if you intend to refer to a component elsewhere in your MXML code,
either in another tag or in an ActionScript block.
The ApplicationControlBar container can be in either of the following modes:
Docked mode
The bar is always at the top of the application’s drawing area. Any
application-level scroll bars don’t apply to the container, so it always remains at the top of the
visible area, and the bar expands to fill the width of the application. To created a docked
ApplicationControlBar container, set its dock property to true.
Normal mode The bar can be placed anywhere in the application, is sized and positioned
just like any other component, and scrolls with the application. The ApplicationControlBar
floats if its dock property is false. The default value is false.
N OT E
In contrast to the ControlBar container, it is possible to set the backgroundColor style for
an instance of the ApplicationControlBar. The ApplicationControlBar container has two
styles, fillColors and fillAlpha, that are not supported by the ControlBar container.
ApplicationControlBar layout container
565
The following example shows an application with a simple docked ApplicationControlBar
that includes a MenuBar. The Application also includes an HBox control that exceeds the
application size; when you scroll the application to view the bottom of the HBox control, the
ApplicationControlBar control does not scroll.
<?xml version="1.0"?>
<!-- containers\layouts\AppCBarSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
]]>
</mx:Script>
<mx:XMLList id="menuXML">
<menuitem label="File">
<menuitem label="New" data="New"/>
<menuitem label="Open" data="Open"/>
<menuitem label="Save" data="Save"/>
<menuitem label="Exit" data="Exit"/>
</menuitem>
<menuitem label="Edit">
<menuitem label="Cut" data="Cut"/>
<menuitem label="Copy" data="Copy"/>
<menuitem label="Paste" data="Paste"/>
</menuitem>
<menuitem label="View"/>
</mx:XMLList>
<mx:Array id="cmbDP">
<mx:String>Item 1</mx:String>
<mx:String>Item 2</mx:String>
<mx:String>Item 3</mx:String>
</mx:Array>
<mx:ApplicationControlBar id="dockedBar"
dock="true">
<mx:MenuBar height="100%"
dataProvider="{menuXML}"
labelField="@label"
showRoot="true"/>
<mx:HBox paddingBottom="5"
paddingTop="5">
<mx:ComboBox dataProvider="{cmbDP}"/>
<mx:Spacer width="100%"/>
<mx:TextInput id="myTI" text=""/>
<mx:Button id="srch1"
label="Search"
click="Alert.show('Searching')"/>
566
Using Layout Containers
</mx:HBox>
</mx:ApplicationControlBar>
<mx:TextArea width="300" height="200"/>
</mx:Application>
DividedBox, HDividedBox, and
VDividedBox layout containers
The DividedBox layout container lays out its children horizontally or vertically, similar to a
Box container, except that it inserts a divider between each child. You can use a mouse pointer
to move the dividers in order to resize the area of the container allocated to each child. You use
the direction property of a DividedBox container to determine vertical (default) or
horizontal layout. The HDividedBox and VDividedBox containers are DividedBox
containers with horizontal and vertical direction property values.
The following example shows a DividedBox container:
Vertical divider
Horizontal divider
In this example, the outermost container is a horizontal DividedBox container. The
horizontal divider marks the border between a Tree control and a vertical DividedBox
container.
The vertical DividedBox container holds a DataGrid control (top) and a TextArea control
(bottom). The vertical divider marks the border between these two controls.
DividedBox, HDividedBox, and VDividedBox layout containers
567
A DividedBox, HDividedBox, or VDividedBox container has the following default sizing
characteristics:
Property
Default value
Default size
Vertical DividedBox The height is large enough to hold all of its children
at the default or explicit heights of the children, plus any vertical gap
between the children, plus the top and bottom padding of the container.
The width is the default or explicit width of the widest child, plus the left and
right padding of the container.
Horizontal DividedBox The height is the default or explicit height of the
tallest child, plus the top and bottom padding of the container.
The width is large enough to hold all of its children at the default or explicit
widths of the children, plus any horizontal gap between the children, plus the
left and right padding of the container.
Default
padding
0 pixels for the top, bottom, left, and right values.
Default gap
10 pixels for the horizontal and vertical gaps.
For complete reference information, see DividedBox, HDividedBox, and VDividedBox in
Adobe Flex 2 Language Reference.
Creating a DividedBox, HDividedBox, or
VDividedBox container
You use the <mx:DividedBox>, <mx:VDividedBox>, and <mx:HDividedBox> tags to define
DividedBox containers. 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. Typically, you use the
VDividedBox (vertical DividedBox) and HDividedBox (horizontal DividedBox) containers as
shortcuts so that you do not have to specify the direction property.
The following code example creates the image shown in “DividedBox, HDividedBox, and
VDividedBox layout containers” on page 567:
<?xml version="1.0"?>
<!-- containers\layouts\HDivBoxSimple.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
backgroundColor="white">
<mx:Script>
<![CDATA[
private function myGrid_initialize():void {
myGrid.dataProvider = [
{Artist:'Pavement', Album:'Slanted and Enchanted',
Price:11.99, Comment:'One of their best. 4 Stars.'},
{Artist:'Pavement', Album:'Brighten the Corners',
568
Using Layout Containers
Price:11.99, Comment:'My favorite.'}
];
}
]]>
</mx:Script>
<mx:HDividedBox width="100%" height="100%">
<mx:Tree id="tree1"
width="30%" height="100%"
labelField="@label"
showRoot="true">
<mx:XMLList>
<menuitem label="Products">
<menuitem label="Posters" isBranch="true"/>
<menuitem label="CDs">
<menuitem label="Pavement"/>
<menuitem label="Pavarotti"/>
<menuitem label="Phish"/>
</menuitem>
<menuitem label="T-shirts" isBranch="true"/>
<menuitem label="Tickets" isBranch="true"/>
</menuitem>
</mx:XMLList>
</mx:Tree>
<mx:VDividedBox width="70%" height="100%">
<mx:DataGrid id="myGrid"
width="100%" height="100%"
initialize="myGrid_initialize();"
change="currentMessage.text=
event.currentTarget.selectedItem.Comment;"/>
<mx:TextArea id="currentMessage"
width="100%"
height="60"
text="One of their best. 4 Stars."/>
</mx:VDividedBox>
</mx:HDividedBox>
</mx:Application>
Notice that this example does not implement the logic to change the top area of the
VDividedBox container when you selct a node in the Tree control.
DividedBox, HDividedBox, and VDividedBox layout containers
569
Using the dividers
The dividers of a DividedBox container let you resize the area of the container allocated for a
child. However, for the dividers to function, the child has to be resizable, that is, it must
specify a percentage-based size. So, a child with an explicit or default height or width cannot
be resized in the corresponding direction using a divider. Therefore, when you use the
DividedBox container, you typically use percentage sizing for its children to make them
resizable.
When you specify a percentage value for the height or width properties of a child to make it
resizable, Flex initially sizes the child to the specified percentage, if possible. Then Flex can
resize the child to take up all available space.
You can use the dividers to resize a percentage-sized child up to its maximum size, or down to
its minimum size. To constrain the minimum size or maximum size of an area of the
DividedBox, set an explicit value for the minWidth and minHeight properties or the
maxWidth and maxHeight properties of the children in that area.
Using live dragging
By default, the DividedBox container disables live dragging. This means that the DividedBox
container does not update the layout of its children until the user finishes dragging the
divider, when the user releases the mouse button on a selected divider.
You can configure the DividedBox container to use live dragging by setting the
liveDragging property to true. With live dragging enabled, the DividedBox container
updates its layout as the user moves a divider. In some cases, you may encounter decreased
performance if you enable live dragging.
Form, FormHeading, and FormItem
layout containers
Forms are one of the most common methods that web applications use to collect information
from users. Forms are used for collecting registration, purchase, and billing information, and
for many other data collection tasks.
570
Using Layout Containers
About forms
Flex supports form development by using the Form layout container and several child
components of the Form conta