A place to share and follow researchSubmit an Article or Content File →

Adobe.Flex 3.0.For.Dummies

loading
Loading file Wait!

spine=.864 Get going with Flex, and create RIAs in a Flash! Develop interactive applications without worrying about browser differences Flex lets you leverage the power of Adobe's ubiquitous Flash technology to build large applications. If you're eager to create Flex apps and you've written code in any language, this book will get you started, introduce you to Flex Builder and the Flex framework, and have you building some really flashy stuff before you know it! Doug McCune is a developer and Flex fanatic who has created several popular applications and Flex add-ons. Deepa Subramaniam is a computer scientist on the Flex Framework team.

Explanations in plain English ? et in, get out? infor ation Icons and other navigational aids Tear-out cheat sheet Top ten lists dash of hu or and fun Gm

Am ISBN 978-0-470-27792-8 $29.99 US $32.99 CN £15.99 UK Internet/Web Page Design Use the event model Work with ActionScript® and MXML Create, run, and debug a project Build simple user interface controls Set up data binding Explore styling and skinning

Companion Web site Go to www.dummies.com/ go/adobeflexfd Find code listings used in the book Use it to create your own cool RIAs liil r i rt I

® Doug McCune Deepa Subramaniam F ex you powe o create R ch nternet App cat ons

Adobe® Flex® 3.0 For Dummies® Published by 111 River Street Hoboken, NJ 07030-5774 www.wiley.com Copyright © 2008 by Wiley Publishing, Inc., Indianapolis, Indiana Published by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permit- ted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions.

Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United States and other countries, and may not be used without written permission. Adobe and Flex are regis- tered trademarks of Adobe Systems Incorporated. All other trademarks are the property of their respec- tive owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITH- OUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FUR- THER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFOR- MATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.

For general information on our other products and services, please contact our Customer Care Department within the U.S. at 800-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.

Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.

About the Authors Doug McCune is a passionate Flex developer, consultant, and community contributor. He has been developing Flex applications since 2004 and is cur- rently a Principal Software Engineer at Universal Mind. Doug received a Bachelor of Arts degree in Science, Technology, and Society from Stanford University. Doug is active in the Flex open-source community and maintains a blog of his thoughts, code samples, and tutorials at www.dougmccune.com. He co-founded FlexLib, a leading resource for open-source Flex components created by community developers. Doug also enjoys speaking at Flex and Flash conferences ? he has spoken at 360|Flex and Flash on the Beach.

Deepa Subramaniam is a Computer Scientist working on the Flex Framework team at Adobe. She joined Macromedia/Adobe in 2003, straight out of University of California, Berkeley where she received her Bachelor of Arts degree in Computer Science (Go Bears!). Deepa joined the early efforts that culminated in Flex 1.0 and has been working on Flex ever since. She might be described as one of the most enthusiastic Flex team members and is thrilled to be working with such bright engineers on such a cool product. Deepa is an active member of the Flex community, often speaking at large Flex and RIA con- ferences like Adobe MAX and 360|Flex. You can learn more about Deepa at her Web site, which includes her popular Flex blog, at www.iamdeepa.com.

Dedication We dedicate this book to Doc, for always keeping us on the clock and in good spirits.

Authors' Acknowledgments We would like to thank Katie Feltman, Kim Darosett, and everyone else at Wiley who made this book happen. Thank you for believing in us and pushing us to the finish line. We also want to thank Darron Schall for his superb tech- nical editing of the book. And finally, we would like to thank everyone at Adobe, especially the Flex and Flex Builder teams, for encouraging us and offering technical support whenever we needed it. You guys are just awesome.

Doug's Acknowledgments I would like to thank the loving and beautiful Jocelyn Sze ? your patience and support during this process have been invaluable. You are my favorite. I also want to thank my father. As I write this, he is in the middle of the ocean sailing single-handedly across the Atlantic. Thank you, Dad, for never ceasing to inspire.

Deepa's Acknowledgments This book would not have been possible without the love and encouragement of my amazing parents, S.N.P (Sam) and Amirtham Subramaniam, as well as my rocking sister, Suguna. They never waver with their loving support, and for this, I am ever thankful. Much love Amma, Appa, and Goons! A big thank you also goes to my extended group of friends who have listened to me chat- ter away about this book, Flex, and my life in general. Your friendship means so much to me.

Publisher's Acknowledgments We're proud of this book; please send us your comments through our online registration form located at www.dummies.com/register/.

Some of the people who helped bring this book to market include the following: Acquisitions and Editorial, and Media Development Project Editor: Kim Darosett Senior Acquisitions Editor: Katie Feltman Copy Editor: Becky Whitney Technical Editor: Darron Schall Editorial Manager: Leah Cameron Media Development Project Manager: Laura Moss-Hollister Media Development Assistant Project Manager: Jenny Swisher Media Development Assistant Producers: Angela Denny, Josh Frank, Shawn Patrick, and Kit Malone Editorial Assistant: Amanda Foxworth Sr. Editorial Assistant: Cherie Case Cartoons: Rich Tennant (www.the5thwave.com) Composition Services Project Coordinator: Erin Smith Layout and Graphics: Ana Carrillo, Nikki Gately, Laura Pence, Christin Swinford, Christine Williams Proofreaders: Melissa Bronnenberg, Christine Sabooni Indexer: Potomac Indexing, LLC

Introduction ................................................................ 1

Part I: Introducing Flex ................................................ 7

Chapter 1: Getting to Know Flex ...................................................................................... 9

Chapter 2: Building Your First Flex Application .......................................................... 17

Chapter 3: Flexing Your Muscle with MXML and ActionScript.................................. 27

Part II: Using Flex Builder (The Flex IDE)................... 51

Chapter 4: Flex Builder: The Best Flex Development Tool ......................................... 53

Chapter 5: Introducing Flex Builder for Developers.................................................... 75

Chapter 6: Visually Designing Applications in Flex Builder ..................................... 101

Charting Components ............................................... 127

Chapter 7: Simple User Interface Controls ................................................................. 129

Chapter 8: Data-Aware User Interface Controls ......................................................... 157

Chapter 9: Forms, Formatters, and Validators .......................................................... 189

Chapter 10: Containers and Navigators ...................................................................... 219

Chapter 11: Charting Components .............................................................................. 253

Part IV: Working with Data in Flex ........................... 283

Chapter 12: The Power of Data Binding ...................................................................... 285

Chapter 13: Working with Data Collections................................................................ 297

Chapter 14: Working with Remote Data ...................................................................... 309

Part V: Exploring Advanced Flex Topics ..................... 321

Chapter 15: Working with Managers We Actually Love ............................................ 323

Chapter 16: Custom Components and Component Architecture............................ 333

Chapter 17: Understanding States and Effects........................................................... 347

Chapter 18: Styling and Skinning Flex Components .................................................. 363

Part VI: The Part of Tens .......................................... 381

Chapter 19: Ten Open-Source Flex Libraries.............................................................. 383

Chapter 20: Ten Flex Resources................................................................................... 391

Index ...................................................................... 397

Introduction ................................................................. 1

About This Book .............................................................................................. 1

Foolish Assumptions ....................................................................................... 2

Conventions Used in This Book..................................................................... 2

How This Book Is Organized .......................................................................... 2

Part I: Introducing Flex .......................................................................... 3

Part II: Using Flex Builder (The Flex IDE) ............................................ 3

Part III: The Flex Framework and Charting Components.................. 3

Part IV: Working with Data in Flex ....................................................... 3

Part V: Exploring Advanced Flex Topics............................................. 3

Part VI: The Part of Tens ....................................................................... 4

Companion Web site ............................................................................. 4

Icons Used in This Book ................................................................................. 4

Where to Go from Here ................................................................................... 5

Part I: Introducing Flex................................................. 7

Using Flex to Develop Rich Internet Applications ....................................... 9

Understanding what an RIA is .............................................................. 9

Taking a look at the rise of Flex ......................................................... 10

Defining Flex ......................................................................................... 10

What's next? ......................................................................................... 12

Comparing Flex to Flash, AJAX, and Silverlight ......................................... 12

Flex versus Flash .................................................................................. 12

Flex versus AJAX .................................................................................. 13

Flex versus Silverlight ......................................................................... 14

Taking Flex to the Desktop with AIR ........................................................... 15

Creating a Flex Project in Flex Builder ........................................................ 17

Writing Code for Your Project ..................................................................... 20

Deciphering the default code ............................................................. 21

Creating the Hello World application................................................ 21

Viewing Your Application in Design Mode ................................................. 23

Running the Application ............................................................................... 25

Introducing MXML ......................................................................................... 28

Comparing MXML and HTML ............................................................. 29

Nesting MXML containers................................................................... 29

Introducing ActionScript .............................................................................. 30

Understanding objects and classes ................................................... 31

Defining getters and setters ............................................................... 33

Learning to love the black box ........................................................... 34

Recognizing that packages are where classes live .......................... 35

Inheritance: Extending a class............................................................ 36

Understanding interfaces.................................................................... 37

Exploring static methods and variables ........................................... 38

Comparing ActionScript and JavaScript ........................................... 40

Working with the Event Model .................................................................... 42

Adding event listeners with MXML.................................................... 43

Examining the structure of an event listener ................................... 44

Adding event listeners with ActionScript ......................................... 45

Understanding event propagation ..................................................... 47

Listening for some common events .................................................. 49

Part II: Using Flex Builder (The Flex IDE) ................... 51

What's Flex Builder, and Why Should I Care? ............................................ 53

Installing Flex Builder .......................................................................... 54

Taking a look at the Flex Builder perspectives ................................ 56

Customizing perspective views ......................................................... 58

Creating Different Types of Projects in Flex Builder................................. 59

Flex Projects ......................................................................................... 60

ActionScript Projects .......................................................................... 63

Flex Library Projects ........................................................................... 65

Organizing and Editing Your Projects......................................................... 65

Editing existing project settings ........................................................ 67

Deleting projects .................................................................................. 68

Software Development Kit (SDK) ................................................... 68

Importing and Exporting Existing Flex Builder Projects .......................... 69

Importing a project .............................................................................. 69

Exporting a project as an archive ...................................................... 70

Running and Releasing Your Projects......................................................... 71

Building and cleaning your projects ................................................. 71

Running your projects......................................................................... 72

Releasing your projects ...................................................................... 73

Accessing Flex Builder Help Materials........................................................ 74

Anatomy of an MXML File............................................................................. 75

Including ActionScript with the tag........................... 77

Introducing the tag ........................................................ 78

Developer Tips and Tricks ........................................................................... 79

Get the hint: Code hinting................................................................... 79

Going straight to the source code ..................................................... 81

Using automatic builds ....................................................................... 82

Organizing import statements ........................................................... 82

Squashing Bugs with the Visual Debugger ................................................. 84

Launching the debugging perspective .............................................. 84

Using breakpoints to step through code .......................................... 84

Inspecting variables............................................................................. 86

Profiling Your Application ............................................................................ 87

Taking out the garbage: The Garbage Collector .............................. 87

Profiling memory use .......................................................................... 88

Profiling CPU performance ................................................................. 95

Refactoring Your Code.................................................................................. 97

Changing class names ......................................................................... 97

Changing method and variable names .............................................. 99

Living with limitations....................................................................... 100

Getting to Know Flex Builder Design Mode.............................................. 101

Navigating Through the Design Area ........................................................ 104

Using Pan & Zoom.............................................................................. 104

Showing surrounding containers..................................................... 105

Selecting Controls in the Design Area....................................................... 106

Controlling the Layout and Size of Controls in the Design Area ........... 108

Positioning controls .......................................................................... 108

Snapping controls relative to each other ....................................... 110

Aligning controls ................................................................................ 110

Sizing and resizing controls.............................................................. 112

Inserting Components with the Components View................................. 113

Viewing the Contents of Your Application in Outline View ................... 115

Working with States in States View ........................................................... 116

Choosing a properties inspector view ............................................ 119

Using the properties inspector ........................................................ 120

Setting constraints visually with the Constraints Control ........... 121

Working with Style Sheets in CSS Design Mode....................................... 123

Charting Components................................................ 127

Taking a Look at Simple Clickable Controls ............................................. 130

Creating button-based controls ....................................................... 130

Popping open controls with ComboBox and ColorPicker............ 139

Making dates: Using calendar controls in Flex............................... 140

Scrolling around ................................................................................. 143

Sliding around with Slider controls ................................................. 144

Introducing Text Controls .......................................................................... 145

Displaying text in Flex ....................................................................... 145

Exploring text-input controls ........................................................... 146

Working with HTML text ................................................................... 149

Showing Off with the Flex Media Controls ............................................... 149

Displaying images .............................................................................. 149

Playing video ...................................................................................... 151

Playing audio ...................................................................................... 151

Showing progress with ProgressBar ............................................... 153

Tying It Together: A Video Player Example ............................................. 154

Recognizing That Awareness Comes from the dataProvider ................ 158

Creating Flash Data Objects in MXML and ActionScript ........................ 158

Array .................................................................................................... 158

XML ...................................................................................................... 159

XMLList ............................................................................................... 160

Creating Flex Data Objects in MXML and ActionScript .......................... 160

ArrayCollection .................................................................................. 161

XMLListCollection.............................................................................. 161

Powering Your Data-Aware Control with Data ........................................ 162

Scrolling List Controls................................................................................. 163

Exploring the scrolling List controls ............................................... 164

Making List controls display text..................................................... 166

DataGrid Controls for Powerful Data Display .......................................... 168

DataGrid .............................................................................................. 169

DataGridColumn................................................................................. 170

AdvancedDataGrid............................................................................. 171

Hierarchical Data Controls ......................................................................... 173

Growing a Flex Tree ........................................................................... 173

Navigating Flex applications with Menus and MenuBars ............. 174

Advanced Functionality in Data-Aware Controls .................................... 180

Scrolling in List, DataGrid, and hierarchical data controls .......... 180

and hierarchical data controls ..................................................... 181

Setting variable list row heights ...................................................... 182

Data-Aware Controls for Customizing the Display of Items ................... 183

Drop-in renderer ................................................................................ 183

In-line item renderer .......................................................................... 184

with Multiple Inline Item Renderers ...................................................... 185

Delving into Form Layouts ......................................................................... 190

Form: Recognizing the top dog ........................................................ 191

FormHeading: Creating labels for different content areas ........... 192

FormItem: Creating individual form elements ............................... 193

Default Button: Helping out the end user ....................................... 195

Validate Me................................................................................................... 196

Customizing visual cues for validation errors ............................... 196

Setting important properties on validators.................................... 197

Triggering validation ......................................................................... 200

Listening for validation events......................................................... 201

Checking out out-of-the-box Flex validators................................... 203

Format Me..................................................................................................... 209

Formatting data .................................................................................. 209

Handling formatting errors ............................................................... 211

Tying It All Together: Creating an E-Commerce Form ............................ 215

Introducing Basic Containers..................................................................... 219

Understanding common container behavior ................................. 220

Starting with a blank Canvas ............................................................ 223

Positioning items by using constraint-based layout ..................... 224

Managing your layout with box layout containers ........................ 225

Creating a tiled layout with the Tile container .............................. 228

Using the Grid container ................................................................... 229

Discovering Panel Containers and Control Bars ..................................... 231

Panel .................................................................................................... 231

TitleWindow ....................................................................................... 233

Alert ..................................................................................................... 235

Control bars........................................................................................ 237

Getting Up to Speed on Navigators ........................................................... 239

Switching between views with the ViewStack................................ 239

Controlling a ViewStack with navigation bar controls.................. 240

Improving navigation with an Accordion ....................................... 242

Creating tabs with the TabNavigator .............................................. 245

Optimizing performance with deferred instantiation ................... 246

Tying It Together: Building a Form with Multiple Parts ......................... 248

Filling Your Charts with Data ..................................................................... 254

Using the right series ........................................................................ 254

Specifying the right fields ................................................................. 254

Creating a ColumnChart and BarChart ..................................................... 256

Clustering ............................................................................................ 257

Stacking ............................................................................................... 257

Designing a LineChart and AreaChart....................................................... 259

LineChart ............................................................................................ 260

AreaChart ............................................................................................ 261

Making a PieChart........................................................................................ 262

Going the simple route ...................................................................... 263

Doing a donut shape.......................................................................... 264

Exploding wedges .............................................................................. 265

Building a PlotChart and a BubbleChart .................................................. 267

Introducing the CandleStickChart and HLOCChart................................. 269

Working with Axes....................................................................................... 269

Adding Legends to Your Charts................................................................. 272

Adding Interactivity..................................................................................... 273

Animating Your Charts ............................................................................... 274

Tying It Together ......................................................................................... 276

Part IV: Working with Data in Flex ............................ 283

Understanding the Data Binding Expression ........................................... 285

Using Data Binding in MXML...................................................................... 286

in-line in MXML tags....................................................................... 286

MXML tag .............................................................. 287

a data binding expression ............................................................. 288

What Properties Support Data Binding?................................................... 289

Moving Forward: Advanced Data Binding ................................................ 290

Binding to multiple destinations or sources .................................. 290

Constructing a bidirectional data binding expression.................. 292

Debugging Data Binding Expressions ....................................................... 292

Using Bindable Metadata ............................................................................ 293

Why Use Flex Data Collections?................................................................. 297

Creating ArrayCollections .......................................................................... 298

Using MXML to create an ArrayCollection ..................................... 298

Using ActionScript to create an ArrayCollection........................... 299

Creating XMLListCollections...................................................................... 300

Using MXML to create an XMLListCollection................................. 300

Using ActionScript to create an XMLListCollection ...................... 301

Common Collection Properties You Should Know ................................. 302

Sorting and Filtering Collections ............................................................... 303

Sorting Flex collections ..................................................................... 303

Filtering Flex collections ................................................................... 305

Accessing Data Items ................................................................................. 306

Connecting with HTTP ................................................................................ 309

Loading your own XML file ............................................................... 310

Asking for what you want ................................................................. 312

Loading someone else's data ........................................................... 313

Understanding the Flash security restrictions .............................. 315

Connecting with Web Services .................................................................. 316

Losing Weight with AMF Remoting ........................................................... 320

Part V: Exploring Advanced Flex Topics ...................... 321

Dragging and Dropping with the DragManager ....................................... 324

The FocusManager: Managing Which Controls Have Focus .................. 325

Popping Up Dialog Boxes with the PopUpManager ................................ 327

Show Me the ToolTips: Using the ToolTipManager ................................ 330

SystemManager: The Engine Behind Your Application..........................332

Looking at the Flex Component Life Cycle ...................................................333

Property invalidation: commitProperties....................................... 334

Size invalidation: measure() ............................................................. 336

Drawing and layout invalidation: updateDisplayList() ................. 337

Creating Reusable Custom Components .................................................. 337

Defining the interface ........................................................................ 338

Choosing your base wisely ............................................................... 338

Adding child components................................................................. 340

Choosing between MXML and ActionScript ................................... 341

Defining your properties ................................................................... 342

Discovering how to talk with events ............................................... 342

RatingSelector component............................................................ 343

Using your shiny, new component .................................................. 344

Working with View States ........................................................................... 347

Creating view states with Design View ........................................... 348

States under the hood ....................................................................... 352

Switching between states ................................................................. 352

Adding Effects to Your Application........................................................... 354

Pulling the trigger .............................................................................. 354

Starting with simple movement ....................................................... 355

Turning your world upside down .................................................... 357

Zooming in and out............................................................................ 358

Wiping that look off your face .......................................................... 359

Running multiple effects ................................................................... 360

Combining States and Effects by Using Transitions ............................... 362

Styling............................................................................................................ 364

Applying styles with MXML .............................................................. 364

Using the block ............................................................... 365

Attaching an external style sheet .................................................... 368

Changing styles with ActionScript................................................... 368

Working with fonts ............................................................................ 370

Understanding the limitations of styling ........................................ 372

Skinning......................................................................................................... 372

Using graphical skins......................................................................... 373

Simple example: Skinning a Button control.................................... 373

Extended example: Skinning a Panel container ............................. 376

Part VI: The Part of Tens........................................... 381

Index ....................................................................... 397

Introduction T here has never been a better time to be a software developer. Web-based applications have come a long way since the early 1990s. You can now create applications that provide amazingly rich experiences, all of which can be delivered through a simple Web browser to any computer in the world. Rich Internet Applications (RIAs) aren't just a passing fad; they signal the emergence of a new breed of powerful, immersive applications that will lead the evolution of the Web.

Flex is on the forefront of this movement. And, the fact that you took the first step by picking up this book means that you're part of this exciting time. RIA developers are making applications that people didn't think were possible. With Flex, you can create full enterprise-scale Web applications that have as much interactivity as the best desktop applications. Flex enables some excit- ing possibilities. We hope that this book exposes this powerful technology to a much wider audience and lowers the barrier for new developers.

Flex lets you leverage the power of the Adobe Flash technology to make large applications. And, because Flash is deployed on nearly all Internet-connected computers, you're developing for a near-ubiquitous platform without ever having to worry about browser differences and incompatibilities. The move to Flex from other Web technologies means that you can focus on creating impressive applications rather than debug in three different browsers. And, because Flex is based on Flash, you can instantly add video and other rich media to your applications.

So, if you're ready to step up your game and start making the next generation of Web applications, crack open this book and get started. Welcome to Flex!

About This Book Most books about Flex are massive and assume that the reader has been programming since age 12. Adobe Flex 3.0 For Dummies, on the other hand, has been written specifically for the beginning Flex developer. If you have heard about Flex, but aren't quite sure what all the buzz is about, this book is for you. We hope that our enthusiasm is contagious because we truly believe that Flex is the most exciting program a software developer can use.

Foolish Assumptions Adobe Flex 3.0 For Dummies is an introductory book, so we don't assume that you already know how to use Flex, although we hope that you know enough about it to realize that it's something you want to use. Part I of this book covers some general programming concepts that you need for develop- ing Flex applications; however, we don't cover the most basic programming topics. If you have experience in writing code in another language, such JavaScript, Java, or C++, you shouldn't have any trouble because we intro- duce ActionScript (which is the language you use for Flex). We do assume that you've written code in another programming language. If you come from a background in using Flash and ActionScript 2, be sure to brush up on the first few chapters to make the transition to ActionScript 3. (After you do, you'll never go back.) We also assume that you have a cursory understanding of HTML. Although Flex doesn't use HTML, some of the markup language used in Flex applica- tions is similar to HTML, and we draw analogies between the two.

Conventions Used in This Book When we mention new terms, we write them in italics, followed by explana- tions of the terms. Also, we include a lot of sample code in this book because we figure that one of the best ways to find out how to write code is to see it. The code in this book appears in a special font, as shown here:

text=?Hello World? How This Book Is Organized Adobe Flex 3.0 For Dummies is organized into six main parts, which contain a total of 20 chapters. Don't feel that you need to read these parts in sequential order; you can jump around as much as you like, and each part is meant to stand on its own. The beginning of the book introduces Flex and some gen- eral programming concepts that are useful if you haven't done much object- oriented programming. Depending on your background, you may want to start by jumping straight to the meat of the Flex framework in Part III, or start at the beginning with an overview of ActionScript and MXML in Part I. Part V is the only part that covers more advanced topics and probably requires that you read some of the earlier content before tackling it.

Introduction 3 Part I: Introducing Flex In Part I, we introduce Flex and the technology that you use to create jaw- dropping RIAs. Chapter 1 describes the evolution of Web technologies and how Flex stacks up against some competing technologies. Without overload- ing you with complex details, we help you jump right into building your first Flex application in Chapter 2. Then, in Chapter 3, we back up a bit and explain some important object-oriented programming principles.

Part II: Using Flex Builder (The Flex IDE) Part II is all about the tool you use to create Flex applications: Flex Builder. Chapter 4 gives you an overview of Flex Builder, and then we divide the content to highlight developer-focused features (Chapter 5) and designer- focused features (Chapter 6).

Part III: The Flex Framework and Charting Components Flex contains a large and powerful toolset of components that you use to create applications. In Part III, we dive head first into the Flex framework and show examples of using all the different components. The chapters in this part are fairly self-contained, although later chapters might reference compo- nents that we cover earlier. Each chapter covers a set of related components, and at the end of each chapter, a larger example ties together all the compo- nents covered in the chapter.

Part IV: Working with Data in Flex Flex applications are only as good as the data that drives them. Chapter 12 covers data binding, which is one key piece that makes Flex development so powerful. Chapter 13 dives into data collections, and Chapter 14 explains how to pull data from other sources on the Web.

architecture and touches on custom component development. Chapters 17 and 18 cover elements that give your applications a bit more kick, such as transitions, skins, and styling.

Part VI: The Part of Tens The Part of Tens consists of a few fun lists that let you continue finding out about Flex after you finish this book. Chapter 19 has a list of ten open-source projects that you can freely use in any of your Flex projects. (Haven't you been dying to play with a 3D engine?) Chapter 20 lists ten resources that are essential bookmarks for all Flex developers.

Companion Web site We write quite a bit of code in this book, but don't worry: You don't have to retype it all by hand. Most of the code that you see here is provided on this book's companion Web site:

www.dummies.com/go/adobeflexfd You can download the code and then copy and paste it directly into your Flex projects.

Additionally, a bonus chapter titled ?Optimizing Your Flex Applications? is available for downloading from the companion Web site. This chapter gives you some optimization tips to help streamline your Flex application's performance.

Icons Used in This Book As you're reading, you'll notice a few funny-looking icons on the edge of the page. Here's what each of these icons means: The Tip icon points out some information that we think is especially impor- tant or interesting. It's often something that might not be obvious but that saves you time and makes Flex development even easier.

This icon marks certain nuggets of information that we think are extra impor- tant to remember. This information is good to drill into your head because we're sure that it will come up repeatedly in your Flex development.

Introduction 5 Sometimes we throw in some extra details that aren't essential but can give you a broader understanding of what's going on behind the scenes. This infor- mation often includes details about the inner workings of Flex.

We all make mistakes, and we use this icon to warn you of potential mistakes (ones we've already made!).

Where to Go from Here If you're brand-new to Flex, the first few chapters provide an overview of the core concepts that become important building blocks. If you already have experience in programming (with ActionScript or a language such as JavaScript), you can probably jump past a chapter or two in Part I. Every chapter in Adobe Flex 3.0 For Dummies is meant to stand on its own, so feel free to jump around as you like and find information in the order that inter- ests you the most.

W e agree with you: Flex can be overwhelming in the beginning. Part I eases you into the world of Flex by introducing the core concepts and providing a bit of context so that you understand how Flex fits in with other, related technologies. Chapter 1 talks about the evolution of Flex and compares Flex with other software products ? and then explains why Flex comes out on top, of course! After getting to know Flex a bit, you jump right in with Chapter 2 and start building an application. Then in Chapter 3, we back up and explain some of the key pro- gramming concepts that you use in Flex development. If you're already familiar with Flex or object-oriented pro- gramming (OOP), you can probably jump straight to Part II. But if you haven't been exposed to OOP principles, take a little time to review these chapters.

Chapter 1 Getting to Know Flex In This Chapter Understanding what Rich Internet Applications (RIAs) are Comparing Flex to other RIA technologies: Flash, AJAX, and Silverlight Taking Flex applications offline by using Adobe Integrated Runtime (AIR) A dobe Flex is an application development platform that you can use to build Rich Internet Applications (RIAs). Flex applications are Web-based, but they provide immersive levels of interactivity and rich media experiences that make them seem more like computer desktop programs than traditional Web applications. Flex is the ideal technology to use when you want to create complex data visualization, performance dashboards, multimedia experiences, and countless other interactive applications. RIAs are raising the bar for Web applications, and Flex is leading the way. In this chapter, we discuss what Flex is, what it isn't, and how it compares to other technologies.

Using Flex to Develop Rich Internet Applications The computer world has come a long way from static HyperText Markup Language (HTML) Web pages. Over the past two decades, rich online experi- ences have gradually evolved into RIAs. Flex is on the forefront of technology that allows you to create such engaging Web-based applications, but it has taken nearly 20 years since the first HTML page was created to get to where we are now. (See the nearby sidebar for more on the journey from HTML to RIA.)

load data within the application. Simple HTML Web pages require a full page refresh to load new data. RIAs, on the other hand, load data asynchronously, which means they can load chunks of data without requiring page refreshes and they keep track of the application state in memory. Flex applications are stateful clients, which means they store data about the current state of the application, such as the content of a shopping cart, in memory in the client.

Asynchronously loading XML is an integral part of all RIA technologies (not only Flex). Version 4 of Flash, which was released in 1999, was the first version of Flash that let developers load external XML data into Flash applications.

Taking a look at the rise of Flex Macromedia, which Adobe later acquired, introduced the first version of Flex in March of 2004. Initially, the first two major releases, Flex 1 and 1.5, were expensive server-based products. A license for Flex 1.5 cost about $15,000, and you had to deploy a server application that would compile your Flex applications and serve them to the user. These initial versions of Flex were based on Flash Player 7 and ActionScript 2, and the code editor was based on the Macromedia Dreamweaver editor.

The release of Flex 2 marked a dramatic shift in the product line. Flex 2 was no longer a server technology at all; instead, Flex was a completely client- side product. The cost dropped dramatically, and Adobe rewrote the entire Flex framework and the Integrated Development Environment (IDE) from the ground up. Flex 2 was based on Flash Player 9 and ActionScript 3, which brought serious performance gains.

Flex 3 added additional functionality to Flex Builder, such as refactoring and enhanced styling support, as well as new data visualization components in the Flex framework. Flex 3 also marked the official open-source release of the Flex SDK and Flex compiler. For more on the open-source aspect of Flex, visit http://opensource.adobe.com.

Defining Flex Defining exactly what Flex is can be confusing because Flex actually includes a combination of different technologies. Flex is not a single software product, but instead includes the following four main pieces: Languages: ActionScript 3 and MXML You use a combination of ActionScript, a scripting language, and MXML, a markup language, to create Flex applications. MXML is similar to HTML, so if you have experience creating HTML Web pages, then you should be able to figure out MXML pretty easily.

Chapter 1: Getting to Know Flex 11 Component framework: Flex SDK The Flex SDK (also known as the Flex framework) is a set of user inter- face components, such as lists, buttons, and charts, that you use to build Flex applications. The Flex SDK (with the exception of the charting package) is free and open source.

Integrated Development Environment (IDE): Flex Builder You use Flex Builder to edit your code, compile your applications, debug your code, and profile performance. Flex Builder is an integrated devel- opment environment (IDE) sold by Adobe.

Cross-browser runtime: Flash Player You deploy Flex applications in a Web browser with the Flash Player plug-in. You can also deploy Flex applications as standalone desktop applications by using the Adobe Integrated Runtime (AIR).

From HTML to RIA When programmers began tinkering with the Web, they used HTML to create Web pages that looked like actual pages of a book. These pages contained a bunch of text that someone wrote and published for the world to read. Those were the good old days of choppy animated images and heavy use of the tag, which was about as ?rich? as the Internet got in the early '90s. Then, Web servers became more sophisticated and started serving up dynamic content, depending on what users were looking for or how they inter- acted with the Web site. For the first time, Web pages started turning into Web applications.

Server-side languages, such as Java, PHP, and ColdFusion, increased the capabilities of Web applications on the back-end. An e-commerce site could let you keep track of items in your shopping cart while you browsed the retailer's site, but each time you added an item, the full Web page would have to reload so that the number of items shown in your cart would stay updated. The state of the application was stored completely on the server, either in memory or in a database. Whenever the server wanted to show you something new, you were sent to a new static HTML page.

But then those static Web pages became ani- mated when a small company called FutureWave Software released FutureSplash Animator, which was purchased by Macromedia and renamed to Flash in 1996. A whole new breed of silly animated movies and impressive visual effects appeared. The Flash platform brought a greater level of interactivity to the Web than ever before. Designers could create interactive visual experiences that went far beyond what was possible with simple HTML.

Flash 5 included the ActionScript program- ming language, which turned Flash into much more than a simple animation tool. Developers started creating complex Flash interactive experiences by combining the visual and pro- gramming capabilities to produce full-blown applications within a Web browser. The first RIAs were being created before the term RIA was widely used or understood. Then in 2004 Finally developers had a tool that was specifi- cally for creating RIAs.

Adobe is actively developing Flex 4, codenamed Gumbo. This version will focus on an improved workflow between developers and designers, and will likely include an improved component framework model to more gracefully separate the visual design of your Flex applications from the underlying code. Toward a similar goal, an additional product in the Flex product line (code-named Thermo) will focus specifically on allowing designers to create complex RIA user interfaces and interactions by using a visual editor, which will create Flex application code that the designer and developer can share.

Flex has been largely in a class of its own when it comes to RIA development platforms, but that reign is now being challenged because some serious competitors are entering the RIA market. Microsoft's Silverlight platform and Sun's JavaFX are two RIA development products aimed directly at taking on Flex. Over the next few years, the competition will get serious, which can only be a good thing for all the developers out there. RIA development is an exciting field; you've chosen wisely!

Comparing Flex to Flash, AJAX, and Silverlight Because you bought this book, we assume you've decided that Flex is the right choice for your project. But, if you need to sell the decision to your boss, he or she will probably ask you how Flex compares to related technolo- gies. The following sections summarize some of the key differences between Flex and a few other RIA technologies.

Flex versus Flash Whenever Doug tries to explain what he does for a living, someone always asks whether Flex is Flash. This question quickly leads to a heated discussion about Flash advertisements, and he has to calm everyone down and explain that, fundamentally, Flex is a Flash-based technology, but no, he doesn't make those annoying ads ? he makes applications. Flex is an application development framework and toolset that you can use to create RIAs. These applications are delivered over the Internet by using the Flash Player.

Chapter 1: Getting to Know Flex 13 The Flex framework: Flash has its own component set that has some of the same functionality as the Flex SDK, but it does not provide as many components and does not include charting components, layout contain- ers, and other framework features that are very useful for developing large applications.

MXML: You can use MXML markup to create your Flex applications, but this markup language is not available in Flash. Flash does use the same ActionScript 3 scripting language, however.

A powerful Integrated Development Environment (IDE): Flex Builder was designed specifically to build applications, as opposed to the Flash You can use both tools to create RIAs, but Flex Builder has features like code-hinting, a powerful debugger, and a profiler that make it a more powerful development tool.

You can use Flash, rather than Flex, to create RIAs, but you have to work in the Flash Authoring environment, which means you don't get the benefits of Flex Builder (such as code hinting), and you can't use the MXML markup language. You may find the Flash Authoring tool really helpful if you're creat- ing animated movies. It uses the timeline metaphor when you create anima- tions and includes drawing tools. Flex Builder, on the other hand, is designed for application development, not animation creation. Flex Builder doesn't include any drawing tools, and it has no timeline.

If you have to decide between Flex and Flash for a specific project, think about exactly what kind of project you're working on. Flex excels when you're creat- ing large desktop-like applications, sharing work among a team of developers, or visualizing data with charts and graphs. For other kinds of projects that require complete control over the visual experience, such as games or adver- tisements, Flash might be a more appropriate choice.

Flex versus AJAX Asynchronous JavaScript and XML (AJAX) is a technique that you can use to load data into HTML Web pages without refreshing the full page. Instead of sending a new HTML page to the user's Web browser for every change, AJAX applications send XML asynchronously and update relevant portions of the screen when needed. By using AJAX, you often end up with a much more responsive user interface and a more desktop-like application experience. Flex applications also asynchronously load XML data.

is currently developing Edition 4. JavaScript is currently an implementa- tion of ECMAScript Edition 3. The current version of JavaScript most closely Adobe released ActionScript 3 in 2006, which is based on the preliminary draft of ECMAScript Edition 4. After Ecma officially releases a new version of ECMAScript Edition 4 and Web browsers support an updated version of JavaScript, the JavaScript programming language should become more like ActionScript 3.

Because of the similarities between the ActionScript and JavaScript lan- guages, and their similar approaches to asynchronously loading XML data, the fundamental benefits of Flex have to do with its underlying Flash Player technology. Here's a rundown of some of those benefits: Multimedia capabilities: Flash Player allows you to create a whole range of rich multimedia experiences that you simply can't achieve by using HTML and JavaScript. Flash has powerful graphics capabilities that can do complex drawing and image manipulation. In addition, Flash supports audio and video streaming, so many leading online video sites use it to play video on the Web.

Cross-browser support: You can be sure that any Flex application you develop will look and behave the same way in all browsers on all plat- forms. Web browsers all have their own quirks and idiosyncrasies when When you develop AJAX applications, you need to test your application in multiple Web browsers to make sure your application is compatible with them all. However, because Flex applications rely on the Flash Player, you can be assured that your application will look the same, pixel for pixel, and behave the same across all browsers.

Flex versus Silverlight Microsoft's competitive RIA technology is Silverlight, a browser plug-in, like Adobe's Flash Player. Just like you have to install the Flash Player plug-in to run Flex applications, you need the Silverlight plug-in to run Silverlight appli- cations. Because Silverlight is fairly new, the Silverlight plug-in isn't nearly as common as Flash Player. Silverlight will likely become more widely used in the future, but right now, the Flash Player plug-in has a strong advantage because of the large number of computers on which it is installed.

The first release of Silverlight 1.0 included the browser plug-in and focused on streaming video on the Web. This release certainly competed with Flash Player because it focused on some of the media features of Flash, but it didn't really threaten Flex's position because Silverlight 1.0 didn't contain a set of user interface controls that you could use to build RIAs. Silverlight 1.0 pro- vided all the low-level graphics capabilities but none of the application frame- work pieces.

Chapter 1: Getting to Know Flex 15 In early 2008, Microsoft released the first beta version of Silverlight 2.0 (origi- nally named Silverlight 1.1), which included a set of UI controls, such as a DataGrid, CheckBox, and Slider. These new controls make Silverlight a closer competitor with Flex. The competition between Flex and Silverlight has just begun, and it's too early to draw any firm conclusions about how serious a competitor Silverlight will become.

Taking Flex to the Desktop with AIR Adobe developed Adobe Integrated Runtime (AIR), previously code-named Apollo, to let you deploy Flex applications as computer desktop applications. By using AIR, you can create your own desktop applications that can run natively on Windows, Mac, and Linux operating systems. You can create AIR applications as Flex applications or AJAX applications, so if you know how to create Flex or AJAX applications, you can create desktop applications, too.

When deciding whether AIR is the right technology for your application, con- sider these three main features that AIR provides: Local file-system access: One of the main reasons for moving from a Web-based Flex application to a desktop AIR application is the inte- grated local file-system access that AIR offers. If you build a Flex-based AIR application, you get a few extra tools that don't come in the normal Flex framework. These tools let you read and write to the user's local file system.

Integrated Web browser: The AIR runtime includes a built-in Web browser: the open-source WebKit browser. This Web browser allows you to load full HTML pages right into your application, something that you can't do in a Web-based Flex application. The AIR framework also lets you display PDF files within your application.

Embedded SQLite database: AIR applications can access an embedded database for offline database access. So, you can build applications that can connect to a server database (like a typical Flex application can) or to an offline database if your application is only occasionally connected to the Internet.

Using the AIR-specific framework controls falls outside the scope of this book. If you're interested in finding out more about AIR, visit www.adobe. com/products/air.

Chapter 2 Building Your First Flex Application In This Chapter Writing your first Flex application Running your application in a browser Editing your code in Source mode Viewing your application in Design mode I n an homage to software examples all over the world, in this chapter you use Flex Builder to write your first Flex application, the classic Hello World, which displays the words Hello World on the screen. While writing this application, you find out how to choose Flex user interface controls, construct an application in the Flex Builder tool, and launch and run the application so that it can be viewed in a browser window.

The focus of this chapter is to show you how to create a quick-and-dirty appli- cation so that you can see how the development tool and framework elements work together. The rest of this book describes Flex Builder (the Flex develop- ment tool) and the Flex framework in more detail. In later chapters, you find out more about how to construct and debug a Flex application, how to deter- mine which elements are available when building your Flex applications, and how to wire them together.

Creating a Flex Project in Flex Builder To write your Hello World Flex application, you use the best tool for writing, debugging, and running Flex applications: Flex Builder. You can use this inte- grated development environment to do the following: Write Flex applications with MXML and ActionScript code.

Visually assemble Flex applications by placing controls on a visual design stage.

Build and run your Flex application in a browser window or as a desktop application.

If you don't have Flex Builder already installed, you can download the free trial version from www.adobe.com/go/flex/. The trial version lets you build full Flex applications for 60 days before deciding if you want to purchase the prod- uct. Refer to Chapter 4 for more detailed instructions on downloading Flex Builder and a description of the different versions of Flex Builder.

To write the Hello World Flex application, you must first create a new project in Flex Builder. Follow these steps: 1. Open Flex Builder.

The first time you launch Flex Builder, the Flex start page opens, as shown in Figure 2-1. This page has all sorts of handy links and informa- tion to help get you started building Flex applications. To get up to speed quickly, check out the tutorials that are linked from the Flex start page.

Figure 2-1: The Flex Builder start page provides many handy tutorials and tips.

Chapter 2: Building Your First Flex Application 19 The New Project Wizard for creating Flex project types appears, as shown in Figure 2-2. The wizard walks you through the steps of creating the project.

Flex Builder organizes its Flex content within projects. You can create several different kinds of projects, depending on what kind of application you want to build. (To find out more about the different kinds of projects available and how to create them in Flex Builder, refer to Chapter 4.) The most common and basic project type is a Flex project. You create this type of project to house your Hello World Flex application. After you've created a project, the other Flex Builder features ? such as the code editor, visual debugger, and visual Design mode ? are available for you to use.

Figure 2-2: The Flex Builder New Project Wizard walks you through creating a Flex project.

3. Enter a project name (for the sample application, enter Hello World) and click Finish.

all projects that exist in your workspace. A workspace is a location that houses all your projects.

A status bar appears at the bottom of the New Project Wizard, indicating that Flex Builder is creating all the necessary files on the file system to house your Hello World project. After the project is created, you see it in Navigator view on the left. A set of folders is created, and the root Flex application for that project opens in Source mode, as shown in Figure 2-3. By default, Flex Builder names the root application for a project main.mxml.

Source mode Design mode Navigator View Figure 2-3: Your new Flex project appears in Navigator view, which lists all proj- ects in the workspace.

Writing Code for Your Project When you create your Flex project, you can start writing code. A simple Flex application, main.mxml, is also created, and Flex Builder opens the MXML application in Source mode (refer to Figure 2-3). This Flex Builder mode offers all the developer-related tools, such as code editors, the debugger, and refac- toring options.

Chapter 2: Building Your First Flex Application 21 Deciphering the default code After you create a project, Flex Builder writes the following chunk of code into main.mxml, by default:

The code breaks down as follows: XML declaration: An XML declaration tag appears at the top of the application, identifying the document as an XML document.

Application MXML tag: Below the XML declaration is the Application MXML tag, which is the root tag of any Flex application. The Application tag has some important jobs, such as expressing the namespace of the controls used in the application. By default, Flex Builder autogenerates code that fills in the mx namespace (xmlns:mx=?http://www.adobe.com/2006/mxml?), which is the namespace where the Flex controls and containers live. You can see this namespace declaration directly in the Application tag.

Attribute declaration: Following the namespace declaration on the Application tag is an attribute declaration. The layout attribute determines which type of visual layout the Application control invokes when positioning its children. By default, Flex Builder sets the layout property to the value absolute, which means that the child elements of the Application control are all positioned at explicit x and y locations within the document.

Closing Application tag: Because all XML tags must be closed, Flex Builder adds the closing tag to make the docu- ment valid.

Creating the Hello World application You know that you want to create a Flex application that simply displays Hello World when it's run. The Flex framework has a variety of user interface controls that can be used to display information in a Flex application. (To find out more about all the available Flex user interface controls, refer to Part III of this book.) One simpler control that you can use is the Flex Label control. This display-only text control writes text to the screen. You can create a Flex Label control by using the MXML tag. The contents of the Label control (the text that it chooses to display) is set in the text attribute to a value that is a String object.

Follow these steps to use the Label control to display Hello World in your application: 1. Write an tag directly in the MXML code editor, which opens by default when you create a new Flex project.

Flex Builder's code hinting feature uses built-in intelligent heuristics to suggest different tags and attributes based on the characters you're typing. As you start typing an opening tag, <, Flex Builder makes com- ponent suggestions in a drop-down list. As you continue typing the mx: namespace prefix and the first letter of Label, L, Flex Builder narrows its suggestions to match the characters you type. After you type the L, Flex Builder suggests the Label component, as shown in Figure 2-4. You can press Enter to autofill the Flex Builder suggestion, or you can finish typing on your own.

Now that you have created a Label control in your Flex application, you need to tell it to display the words Hello World. This task is simple ? a Label control uses the text attribute to specify the text it should display.

Figure 2-4: The code hinting drop-down list gives you sugges- tions as you enter code in the code editor.

2. Directly in the Label MXML tag, add the following code: text=?Hello World!? You may have noticed, as you add the text attribute to the Label tag, that Flex Builder suggests other attributes that can be set on a Flex Label control. Flex Builder provides not only tag-level code hinting but also attribute code hinting.

Chapter 2: Building Your First Flex Application 23 based on their x and y properties. Because the Label control hasn't specified an explicit x, y position, the Application container places the Label control at its default position: 0,0. This position indicates that the Label control lives at the upper-left corner of the screen.

If you center the Label control within your application, you can create a more visually pleasing effect. You can easily use the built-in layout con- straints, where user interface controls are constrained to the edges of their parent container. (To find out more about layout constraints, refer to Chapter 10.) 3. To center the Label control, add one center constraint to the Label tag Add this code to the Label MXML tag: horizontalCenter=?0? The horizontalCenter constraint is set to a pixel value that determines the distance between the center of the control and the center of its parent container. Setting the Label's horizontalCenter attribute to a value of 0 perfectly centers the control in the center of the application.

When you're finished, your code should look like this (see Figure 2-5):

Figure 2-5: The finished code for your Hello World Flex application.

tab in the upper-left toolbar in Source mode (refer to Figure 2-3). (To find out more about Flex Builder Design mode and how to author and modify Flex applications and components visually, refer to Chapter 6.) When you click the Design tab, Flex Builder changes to Design mode, shown in Figure 2-6. This view has a design stage that shows how the application's current state appears. Additionally, you can use the panels flanking the design stage to drag new Flex components to add to the design and to edit existing components. Whenever anything is done in Design mode that changes the state of the application (for example, dragging out a new component or changing a component property), the corresponding code is added or modified in Source mode. Everything done in Design mode results in generating or modifying the correct code in Source mode. Similarly, every change you make in Source mode gets represented in Design mode.

In Figure 2-6, you can see that the design stage shows a Flex Label component centered in the Application container. That's how your Hello World appli- cation will look in the browser when you run it.

Run button Design stage Figure 2-6: Design mode ren- ders an application to indicate what it will look like when you run it.

Chapter 2: Building Your First Flex Application 25 Running the Application Flex Builder is a one-stop tool for all your Flex development needs. Within Flex Builder, you can write, run, and debug applications. Before you can run a Flex project, however, you need to build it. Building a project means that you invoke a compiler ? in this case, the Flex MXML compiler ? to compile code and check for errors. If errors exist, you need to fix them and then build the project again. After the project is successfully built, you can run it and view your Flex application in a browser window.

When you launch a Flex application, you're building the application, check- ing for errors, and then running the application in a browser window. Flex Builder offers a variety of toolbars that have buttons for invoking different actions, such as running, debugging, or profiling an application. To launch your Hello World project, click the Run button on the main code toolbar (refer to Figure 2-6), which is available in either Source mode or Design mode. Flex then builds the application and launches it in a browser window. By default, Flex Builder launches the application in your computer's default Web browser.

If problems exist in your application code, you see them written out to Problems view, at the bottom of the code editor window. If no errors exist, your application is launched in the default browser window, and you should see your application running! The result of the Hello World program looks like Figure 2-7.

There you go. In just a few, simple steps, you built a simple Flex applica- tion in Source mode, viewed it in Design mode, and ran the application in a browser window.

Figure 2-7: Running the application launches a browser window showing the finished product.

Chapter 3 Flexing Your Muscle with MXML and ActionScript In This Chapter Understanding MXML and ActionScript Developing object-oriented applications Using inheritance and interfaces Working with the event model F lex applications are created by using a combination of the declarative markup language MXML and the scripting language ActionScript. You use both MXML and ActionScript, often together, to create your projects. If you're familiar with developing AJAX Web applications, try drawing an analogy between HTML and JavaScript. When you create AJAX applications, you use HTML as the declarative markup language to lay out the user interface elements of your appli- cation, and then you use JavaScript to add interactivity. MXML and ActionScript work much the same way, with MXML often serving to create the visual layout of your application and ActionScript adding powerful programming capabilities.

In this chapter, we provide an overview of MXML and ActionScript and explain the power and unique capabilities of each technology. To become a successful Flex developer, you should grasp some important general programming concepts, so we cover some object-oriented programming principles and discuss the event model that's used for communication among the different pieces of your application.

In this chapter, we make some assumptions about your programming knowledge. We assume that you have some experience in writing code in a programming language such as JavaScript, Java, C, C++, or Basic and that you have at least a cursory understanding of HTML or XML. Although you certainly don't need to be an expert programmer in any specific language, we don't cover all the small details of fundamental programming concepts. If tasks such as working with for loops, declaring variables, and invoking functions are foreign to you, you may need to spend some time reading about these fundamental concepts because a discussion of that information is outside the scope of this book.

Introducing MXML MXML is a tag-based declarative markup language that you use to compose Flex applications. When you start a new Flex project, you begin with a new MXML file. As we explain in Chapter 2, every Flex application starts out as an MXML file with an empty tag. MXML is contained in files that use the .mxml extension.

You create components by creating new MXML tags. The following tag creates a new Button component and sets the label that's displayed on the Button:

By adding that single line to your main application MXML file you have added an interactive Button. The Flex framework contains a number of different user interface controls that you can use in your applications, with the Button being one of the simplest ones. All the Flex framework controls can be added with MXML. Listing 3-1 creates a simple login form, shown in Figure 3-1.

Listing 3-1: A Simple Login Form

Chapter 3: Flexing Your Muscle with MXML and ActionScript 29

For now, don't worry about exactly what the Form or TextInput controls can do; we cover all the controls in later chapters. (We discuss Forms in Chapter 9 and text controls, such as TextInput, in Chapter 7). Notice how the MXML components are defined in Listing 3-1, however, because you use this general syntax throughout your Flex development.

Comparing MXML and HTML If you're familiar with HTML, MXML probably doesn't look much different. But don't let the similarity of the syntax fool you; MXML is completely dif- ferent from HTML. None of the normal HTML user interface components are present. There are some similar components, however, such as TextInput (which can be created with the MXML tag). TextInput is similar to the HTML tag. But even though some of the MXML tags might resemble HTML components, be aware that they are, in fact, different controls.

Nesting MXML containers The Flex containers are a subset of the components in the Flex framework that are specifically designed to hold other controls. A few of the containers that you use in your applications are Canvas, HBox, VBox, and Panel. You can define these containers in MXML and add child components by nesting MXML tags. The following example creates a horizontal box container that holds two Button controls (shown at the top of Figure 3-2):

Because the two tags are placed between the opening HBox tag () and the closing HBox tag (), they are added to the HBox, which lays them out horizontally. You can nest MXML tags within each other multiple levels deep, to produce complex layouts. The following code creates a Panel container that contains an HBox, which contains the two Buttons (as shown at the bottom of Figure 3-2):

Figure 3-2: Using nested containers to lay out Flex Notice how the opening and closing tags for the Panel and the HBox have to completely surround their contents. Make sure that you always properly nest your MXML tags, or else your code doesn't compile. The following is an incorrect example of nesting that generates an error:

If you tried to run the above code the compiler would tell you that you haven't properly closed the HBox tag.

Introducing ActionScript MXML can be great for creating layouts of user interface controls for your applications, but when you need more programmatic control, you use ActionScript. The syntax of ActionScript is close to that of JavaScript and Java (although JavaScript is definitely closest), so if you have experience with either of those languages, the syntax should be familiar.

Chapter 3: Flexing Your Muscle with MXML and ActionScript 31

Making the shift to ActionScript's object-oriented programming ActionScript 3 is an object-oriented programming (OOP) language, which means, in general terms, that the fundamental structural unit of your applica- tion is an object. Objects expose specific functionality in the form of proper- ties and methods, which you use to interact with the objects.

If you have programming experience in earlier versions of ActionScript (1 or 2), the shift to ActionScript 3 may feel daunting. ActionScript 3 forces you to follow stricter OOP syntax when writing code, and you'll notice throughout this book there is never a reference to _root or global variables. If you have a background in other object-oriented programming languages, such as Java or C++, you already have experience in writing OOP applications, and the shift to ActionScript 3 should be fairly painless.

Understanding objects and classes At the heart of object-oriented programming is the object, which encapsu- lates functionality. When an object is encapsulated, it has certain capabilities that it exposes through properties and methods you can use, but it hides all other details about how it does what it does. A class is the definition of an object. An object is one particular instance of a class. Each ActionScript class is defined in its own ActionScript file (with the .as file extension).

To illustrate the concept of a class, think about an employee within an orga- nization. An Employee class might contain the following properties:

firstName lastName socialSecurityNumber salary And, an Employee might have the following actions (methods) that it can perform:

The preceding lists include four properties and four methods of the Employee class. The basic Employee ActionScript class might look like the code in Listing 3-2.

Listing 3-2: The Employee Class with Four Properties and Methods package com.dummies { public class Employee ?3 { public function Employee() ?5 { //in the constructor you can initialize the object }

//define the public variables public var firstName:String; ?11 public var salary:Number;

//define the public methods public function doTask(task:Task):void { ?17 //do something to accomplish the task }

public function takeBreak(minutes:Number):void { } public function submitTimesheet(timesheet:Timesheet):void {

} public function complainAboutBoss():void { } } } Listing 3-2 defines the outline structure of your Employee class: ? 3 You name the class on Line 3, public class Employee, which defines the Employee class, and corresponds with the filename of the ActionScript file in your project. Because this class is named Employee, you have a file named Employee.as in your project.

? 5 The constructor is a special function that creates the object. When a new Employee is created by calling new Employee(); this con- structor (Lines 5?8) is called. In the constructor, you can do any kind of initial setup that your class needs.

Chapter 3: Flexing Your Muscle with MXML and ActionScript 33

? 11 You define a few public properties in Lines 11?14. Other classes can use these properties to interact with the Employee class.

? 17 You also create public methods that are used to interact with the Employee class (Lines 17?31). These methods define all the things an Employee can do.

Defining getters and setters ActionScript has a special syntax to define getters and setters on a class, which are unique ways to combine the functionality of both a variable and a method. Although a getter or a setter looks like a normal variable to the out- side world, when it's accessed, it runs a function. The easiest way to explain getters and setters is by describing the example in Listing 3-3.

Listing 3-3: Defining a Getting and Setter for hourlyRate public class Employee { public var salary:Number;

public function get hourlyRate():Number { } public function set hourlyRate(value:Number):void { this.salary = value * 40 * 50;

} } Listing 3-3 defines a getter and setter for the hourlyRate property of the Employee class. The hourlyRate getter isn't a normal property, however, and is instead determined by the salary property. (In this example, we assume 40-hour workweeks and 50 workweeks in a year.) You can access getters and setters just as you access normal properties of a class. The following code creates a new Employee, sets the salary to $100,000 (we're Flex developers, after all), and then uses the hourlyRate getter:

Because you defined hourlyRate as a getter, you can access it the same way you access a normal property. But when you access the hourlyRate getter, the function you defined runs and performs the calculation.

Because setters work the same way, you can have specific code that runs whenever a certain property is set. In Listing 3-3, the setter for hourlyRate calculates the yearly salary for that rate and sets the salary property.

Learning to love the black box An important concept in object-oriented programming is that every object is a black box, which exposes specific functionality but doesn't let you peer behind the curtain to see the details of the implementation. When you pro- gram in an object-oriented language, you don't need to worry about how a certain class does what it does; all you need to know is which methods and properties you can use. To illustrate this point, we apply the theoretical OOP principle to a real-life example.

If you're like most folks, you have no idea how a microwave oven heats food. You know that seemingly magical invisible rays fly around, but that's about the extent of your understanding. But you know how you're supposed to use a microwave oven: You place food inside it, enter on a keypad the length of time you want the food to cook, and then press the Start button ? and the food is then heated. To you, the microwave is a ?black? box. Here's a simple OOP example that illustrates this concept:

Within the warmUp method, any number of behind-the-scenes events can be happening. For all you know, a thousand gerbils running on treadmills generate an electric current that heats your food. But all you care about are the exposed properties and methods of the Microwave class. You know that you can call the addFood() method and pass in something for it to warm up. And, you know that you can set the time property, which determines how hot the Microwave makes the food. Then you call warmUp(), and you can assume that the Microwave will fulfill its side of the bargain and warm your food. You don't need to know anything about molecular physics to get all those tasks to work. All these pieces, such as the time property and the warmUp() method, define the interface that you use to interact with the Microwave class. The interface is the collection of public properties and methods that a class exposes to the developer.

Chapter 3: Flexing Your Muscle with MXML and ActionScript 35

Object-oriented programming is all about using the exposed interfaces defined by classes and not having to worry about how they do what they do. One out- standing benefit of this approach is that you can completely change the under- lying implementation without affecting the rest of your application. As long as the exposed methods and variables stay the same, all the behind-the-scenes implementation details can change.

Recognizing that packages are where classes live Classes are located in packages, which serve as a way to organize the ActionScript files in your project and to locate the classes within your code. The package of a class is the list of strings separated by periods that precede the class names. All Flex framework classes exist within the mx package, which means that the full package name of every class in the Flex framework resembles mx.subPackage.Class. For example, the full package structure of the Button class is mx.controls.Button. This example shows that the Button class lives in the controls package within the mx package.

When you create your own, custom ActionScript classes, you should use packages to organize your code. Picking a package structure involves orga- nizing your ActionScript files into a series of folders that match the package structure you want to use. You must also ensure that the package definition at the top of your ActionScript class matches the folder structure. The first line in any of your ActionScript classes defines the package for the class by using the package keyword followed by the full package name.

You can pick any package-naming structure you want, although a standard that's often used is the reverse domain name syntax. It uses domain names to uniquely identify packages, but in reverse order. If you take a look at the first line in Listing 3-2, you see the use of the com.dummies package for the Employee class:

package com.dummies { In this line, the Employee.as source file is placed in the com/dummies/ directory within your project, as shown in Figure 3-3.You can use any package-naming scheme that you like; however, it is a common practice to group related classes together under the same package. As you work with the different components within the Flex framework, notice how they are grouped in logical packages, such as mx.controls and mx.containers.

Figure 3-3: Package structure corresponds with folder The package-naming convention you use is arbitrary, and if you choose to use the reverse domain style, it doesn't mean that it needs to map to a real URL. The com.dummies package was used in the example, but that doesn't have any true relationship to the dummies.com domain name.

Inheritance: Extending a class An ActionScript class can extend another class, which means that it inherits all the functionality of the class it's extending. The class can then add func- tionality in addition to what was contained in the base class. In the Employee example in the previous section, you can split the Employee class into two classes. First and foremost, an Employee is a Person, which has certain prop- erties, such as firstName and lastName. The following listing contains a simple Person class:

package com.dummies { public class Person { } } Now that you have a Person class that contains the firstName and lastName properties, you can make the Employee class extend Person, and you can remove the firstName and lastName properties from Employee because they're contained in Person. Here's a portion of the new Employee class:

package com.dummies { public class Employee extends Person { ...

Chapter 3: Flexing Your Muscle with MXML and ActionScript 37

Now that you have the base Person class, you can make other classes that also extend Person. For example, you can make a Boss class that defines the specific functionality of a Boss. The Boss class is shown in Listing 3-4.

Listing 3-4: The Boss Class Extends Person package com.dummies { public class Boss extends Person { public var employees:Array;

public function giveRaise(employee:Employee, percent:Number):void { employee.salary = employee.salary + (employee.salary * percent);

} public function giveRaiseToAll(percent:Number):void { for(var i:int=0; i

} } } } Because Boss also extends Person, you don't have to create the firstName or lastName properties; it inherits those properties just like the Employee class does. But the Boss class contains all elements specific to a Boss. In this example, a Boss has a list of employees and can give raises (which, in an ideal world, the boss would do).

Understanding interfaces An interface, which is a special kind of ActionScript file, is similar to a class but doesn't define any specific implementation details. An interface defines a list of methods, but unlike a class, the interface doesn't have any code to define how the method works. Instead, classes are supposed to implement the interface, which means that the class must include all methods defined in the interface. The following code snippet defines a simple interface named IPayee that has a single function named receiveMoney:

The interface looks similar in structure to a class; however, notice in the third line the use of the word interface rather than the word class. The interface defines a function, although you can see the lack of a public, private, or protected keyword. A class that implements an interface must implement all functions defined in the interface as public functions. You can define only public methods within an interface, not properties. However, because getters and setters are methods, you can define those in an interface as well.

You can modify the Employee class to implement the IPayee interface. To do so, you need to add the implements keyword to the class definition, and you create a method named receiveMoney:

public class Employee extends Person implements IPayee { public function receiveMoney(amount:Number):void { trace(?I'm rich!?);

} To understand the benefit of using interfaces, imagine which kinds of entities the Boss class you created might have to pay. Obviously, all employees need to get paid, but also, possibly, merchants, utility companies, and govern- ment tax boards, for example. In this context, each of these entities could be a completely different class, but they can all implement the IPayee interface, which indicates that each class can receive money. The Boss doesn't need to know about each different class that needs to be paid; instead, the Boss knows only about the IPayee interface, and can know how to interact with any class that implements that interface.

Exploring static methods and variables If a method or variable has the static keyword before the method or vari- able name, it behaves differently from normal variables or methods of the class. Static methods and variables belong to the class itself, not to any par- ticular instance of the class. When you call a static method, you're calling a method on a class, as opposed to a method on an object.

The code in Listing 3-5 creates the CustomMath class, which has two static functions: one for returning the sum of an array of numbers and another for returning the average.

After those static methods are defined in the CustomMath class, you can invoke them by calling CustomMath.sum() and CustomMath.average() ? for example, var avg:Number = CustomMath.average(3, 4, 5). You never create a new instance of the CustomMath class. This usage is wrong, for example: var math:CustomMath = new CustomMath().

Chapter 3: Flexing Your Muscle with MXML and ActionScript 39

Listing 3-5: Creating a Class with Two Static Functions package { public class CustomMath { public static function sum(numbers:Array):Number { var sum:Number = 0;

for(var i:int=0; i

} } } A few main static methods and variables are built into the Flex framework that you will use. The following list describes a few of the most common ones you see while building Flex applications: Application.application: You can always access the main Application object that is the root of your Flex application by using the static variable Application.application.

Alert.show(): The Alert class lets you display pop-up dialog windows by using the Alert.show static function. The following line pops up a window with the title Error and the message Houston, we have a problem.

PopUpManager: The PopUpManager class contains a set of static meth- ods that let you work with your own, custom pop-up windows. The main methods you use are addPopUp, removePopUp, and centerPopUp.

Math: The Math class has a whole series of static math functions, such as min, max, sin, and cos. For example, to compute the lesser of two numbers (defined as variables x and y), you can call var min:Number = Math.min(x, y);

System.setClipboard(): You can set the text that's on the user's Clipboard by calling System.setClipboard(?text to set?). Note that for security reasons, you cannot get text from the Clipboard; you can only set it.

Comparing ActionScript and JavaScript ActionScript and JavaScript are similar languages, and both are based on the same language specification, ECMAScript. The main difference is that ActionScript is an implementation of a newer draft of the ECMAScript stan- dard, Version 4. But because both JavaScript and ActionScript are based on the same base specification, the syntax you use is similar.

One big difference between the two languages involves the strict-typing of ActionScript 3, which supports compile-time type checking. When you declare a variable, you specify which type of variable it is ? a String or Number or any custom class you might be using. The following line of code declares a variable named myDate that is a Date:

Because the myDate variable is declared as a Date object, if you try to assign any value that isn't a Date, the compiler catches it and notifies you. So, the following line generates a compile-time error:

myDate = 5; //won't work because 5 is a Number, not a Date

Having this type of compile-time type checking might not seem like a big deal, but it's invaluable for writing bug-free code. Without compile-time type checking, you can easily write code that makes mistakes that go uncaught. These types of errors would crop up eventually, but only at runtime when you're debugging your application. Compile-time type checking forces you to write clear, structured code that's less prone to errors.

Understanding the Relationship between ActionScript and MXML Every MXML tag is actually ActionScript code behind the scenes. Each of the components in the Flex framework is written in ActionScript. When you compile a Flex application, the compiler translates all the MXML code into pure ActionScript code, which is the code that is then compiled and run. MXML is just a shortcut that makes certain tasks, such as laying out the pieces of the user interface in your application, much easier than having to code the comparable ActionScript by hand. But you should understand that anything you can do with MXML markup, you can also do with ActionScript. Depending on the task, some tasks are easier to do with MXML markup, and some are easier (or only possible) with ActionScript.

Chapter 3: Flexing Your Muscle with MXML and ActionScript 41

MXML helps most in two areas: Application design: MXML simplifies application design when you're composing the visual layout of your applications.

Data binding: MXML lets you use data binding with a simple tag-based syntax. For more on data binding, see Chapter 12.

The following example illustrates how to simplify the layout of your application. Listing 3-6 creates a simple Flex application with a Panel container that contains an Image.

Listing 3-6: Using MXML to Create and Lay Out Your Application

The entire sample application in Listing 3-6 consists of six lines of MXML code. You can create exactly the same application by using almost all ActionScript code, and it would look like the code in Listing 3-7.

Listing 3-7: Using Pure ActionScript to Create and Lay Out Your Application

Listing 3-7 (continued) } ]]>

This listing produces exactly the same application, but it needs four times as many lines of code, which highlights what makes MXML so useful.

Working with the Event Model The Flex framework relies heavily on events as the preferred method of commu- nication between components. An event is an announcement that something has happened. This ?something? might be a mouse click or a notification that a file has finished downloading or anything else that a component wants to tell other components about. Events are a fundamental part of the Flex framework, and you must properly understand how the event model is supposed to work in Flex applications.

All components in the Flex framework define specific events that you can listen for. When something happens within a component that it wants to announce, such as a button click, the component dispatches an event. Dispatching an event is a way to announce that something has happened to all the other parts of your application.

The Button control is a good example for exploring the event model. The Button control primarily displays a button with some text and lets the user click it. An application that uses a Button control doesn't know anything about what happens when the user interacts with the Button. For instance, an appli- cation doesn't care how the Button draws itself when the mouse rolls over or off. All you need to pay attention to are the events that the Button dispatches. The most important event that a Button dispatches is probably the click event. When the Button is clicked, it dispatches a new event to announce that it was clicked. The Button is responsible only for making that announcement and doesn't care which other parts of your application, if any, are listening for the announcement.

Chapter 3: Flexing Your Muscle with MXML and ActionScript 43

the user clicks the control, it dispatches the click event, but the dispatching of that event doesn't do anything on its own. In your application, you attach a listener to the click event, which is a function that`s run when the event fires. After you add a listener, the code within your listener method runs every time that particular event is dispatched.

The words listener and handler are often used interchangeably when talking about events. Adobe has a set of coding guidelines that define their best prac- tices for writing ActionScript 3 code. These best practices recommend names for your event listener methods, such as eventNameHandler, which is the convention we use in this book. So, an event listener for a mouse-down event would be named mouseDownHandler. To review the best practices guide- lines, visit http://opensource.adobe.com/wiki/display/flexsdk/ Coding+Conventions.

Adding event listeners with MXML The easiest way to add event listeners to Flex components is to add MXML attribute listeners. You add event listeners in a similar way as you define properties or styles in the MXML tag. But event listeners are different than properties and styles, because they define ActionScript code that's run when the event fires. You can add a listener to the click event of a Button control, like this:

The click and label are both MXML tags, but the label tag defines a property and the click tag defines an event listener. Event listeners defined inline in this way consist of ActionScript code that's executed when the event fires.

You don't have to point only to a function to handle the event; you can write ActionScript code directly in the MXML tag, if you want. For instance, the fol- lowing example displays an Alert message by using ActionScript code directly in the click MXML tag:

show(`You clicked!')? /> However, as a general practice, code is often much more readable and man- ageable if you always use functions defined outside the MXML tag as your event listeners.

Examining the structure of an event listener The event listener defined in your ActionScript code should be a function that takes a single Event object parameter. Your functions generally look like this:

private function eventHandler(event:Event):void { //do your event handling stuff here }

Notice that the event parameter is an Event object. Event handlers are always passed an Event object that has a few important properties. Most importantly, the Event object has a property named target that identi- fies the component that dispatched the event. Be aware also of a different property named currentTarget. The differences between target and currentTarget are discussed later in this chapter, when we cover event bubbling. For now, just know that you can use target to get a reference to the component that dispatched the event.

The following example displays two buttons, both of which use the same event listener for the click event. The event listener uses the target prop- erty to get a reference to the particular Button control that was clicked, and then displays an Alert pop-up message showing the label of the Button.

} ]]>

Chapter 3: Flexing Your Muscle with MXML and ActionScript 45

on the component. Explicitly casting it to a Button lets you access the Button-specific properties of the object, such as label.

Event is the base class for all events, but more specific classes also extend Event to provide more detailed information about particular kinds of events. For example, mouse interaction events use the MouseEvent class, which adds the localX, localY, stageX, and stageY properties that define the coordi- nates, relative to the component and the stage, of the mouse when the event was dispatched.

The example in Listing 3-8 adds a listener to the change event of a horizontal slider control. When the HSlider dispatches the change event, it dispatches a SliderEvent event, which has a few specific properties that tell you more about the interaction with the slider. In this example, you can access the value property of the event to get the latest slider value.

Listing 3-8: Adding a Listener to the Change Event of a Slider Control

private function changeHandler(event:SliderEvent):void { } ]]>

Many Flex components dispatch their own custom events, so they can indicate this type of detailed information. The documentation for each of the components in the Flex framework explains all the different events that each component dispatches. Giving you a comprehensive list of all events and event types is beyond the scope of this book, although in Part III, we touch on the common events for many of the framework controls.

Adding event listeners with ActionScript You can also add event listeners with ActionScript rather than with MXML tags. All Flex components have a method named addEventListener that you can use. When you call addEventListener, you have to specify which event you're listening for and the handler function that runs when the event is dispatched. The example in Listing 3-9 creates ten Button controls when the application first loads and adds a click event listener to each one.

Listing 3-9: Adding an Event Listener with ActionScript

private function createButtons():void { for(var i:int=0; i<10; i++) { box.addChild(button);

} } private function clickHandler(event:Event):void { } ]]>

When you add the click event listener with ActionScript, you use MouseEvent. CLICK as the event type. This static variable is defined by the MouseEvent class. The MouseEvent.CLICK variable translates to the string click. You can add However, when you add event listeners with ActionScript, you should always use the static variables instead, such as MouseEvent.CLICK. Using the static variables ensures that you don't have any accidental typos in your code, and your code benefits from proper compile-time checking. If you used a string to represent the event type, the compiler can't help look for potential problems. For example, you might type the following line:

button.addEventListener(?rollover?, rollOverHandler) The proper event name, however, is rollOver (notice the capitalization difference). If you use MouseEvent.ROLL_OVER rather than the string, you can always be sure that you're using the correct event type. So, rather than ?rollOver?, the proper way to add the event listener is

Chapter 3: Flexing Your Muscle with MXML and ActionScript 47

One benefit of using ActionScript to add event listeners is that you can remove them by using the removeEventListener method. Only listeners that are added with the addEventListener method can be removed; you cannot remove event listeners that are added with inline MXML tags. If you later want to remove the click listener that you added on one of those but- tons, you can add this line:

button.removeEventListener(MouseEvent.CLICK, clickHandler) Understanding event propagation When an event is dispatched by a component, it propagates up and down the hierarchy of components in your application. During the propagation of a single event, three phases make up the event life cycle: capture, target, and bubble. Event listeners can register and receive notification at any of these three phases: Capture: This phase is the first phase, but is rarely used. In the capture phase, the Event begins at the top-level parent component and works its way down the display list until it reaches the target component that dis- patched the event. In the hierarchy shown in Figure 3-4, the Event begins in the capture phase at the Panel and then moves down to the Hbox and then down to the Button.

When you add an event listener, you have to specify whether the listener should listen in the capture phase. The third parameter in the addEvent Listener method is a Boolean value that determines whether the capture phase is used (it defaults to false). To add a listener to the Button control on the capture phase, you can use the following line of code: button.addEventListener(MouseEvent.CLICK, clickHandler, true);.

For most event handling in your applications, you never need to use cap- ture phase listeners. Unless you need extremely aggressive event han- dling for some reason, you can probably just stick to target and bubble phase listeners.

Target: Because the Button control was the component that dispatched the event, after the event propagates down to the Button, it reaches the targeting phase. This phase is used only for event listeners that target and event.currentTarget are the same).

Bubble: After reaching the targeting phase, the event then propagates back up the display list in the bubbling phase. In the example, the event hits the HBox and then the Panel while bubbling. The order of the bubble phase is the opposite of the capture phase.

Figure 3-4 shows the propagation of an event through the three phases as it travels down the display list and back up.

Figure 3-4: The propa- 1. Capture 3. Bubble gation of a single event through the capture, 2. Target target, and bubble phases.

At any point in your event listeners, you can figure out which phase is active by inspecting the eventPhase property of the Event. The example in Listing 3-10 demonstrates the complete propagation of a single click event. The example adds click event listeners to the Panel, HBox, and Button. When the click event fires. the event listener uses trace() to output debugging information about the event.

Listing 3-10: An Example to Debug Event Propagation

} private function clickHandler(event:MouseEvent):void { trace(?phase: ? + event.eventPhase + ? | target: ? + event.target + ? | currentTarget: ? + event.currentTarget);

Chapter 3: Flexing Your Muscle with MXML and ActionScript 49

When you run the code in Listing 3-10 and click the button, you see the following debugging output:

phase: 1 | target: app.panel.hbox.button | currentTarget: app.panel phase: 1 | target: app.panel.hbox.button | currentTarget: app.panel.hbox phase: 2 | target: app.panel.hbox.button | currentTarget: app.panel.hbox.button phase: 3 | target: app.panel.hbox.button | currentTarget: app.panel.hbox phase: 3 | target: app.panel.hbox.button | currentTarget: app.panel

This chunk of code shows the complete propagation of a single click event. In the sample output, the event phases are displayed as the numbers 1, 2, or 3, which correspond with the capture, target, and bubble phases. The event begins in the capture phase at the top-level Panel container and then travels down the display list, still in the capture phase, to the HBox container. The event then reaches the Button control, and because the Button is the compo- nent that dispatched the event, the event is now in the target phase. (Notice that the target and currentTarget properties of the event are the same.) The event then travels back up the display list in the bubble phase, hitting the HBox first and then the top-level Panel container.

At any point in the event propagation cycle, you can call stopPropagation() or stopImmediatePropagation() on the event, which stops the event in its tracks. The stopImmedaiteProgpagation() event stops the event right away, and no other listeners that are registered for that event are called. If you call stopPropagation() instead, any other event listeners for that event on the same component are executed, but the event doesn't move any farther up or down the display list.

Listening for some common events All components in the Flex framework dispatch a few useful events. The following list describes a few of the common events you might use in your applications: show, hide: Whenever a component's visible property is changed, either the show or hide event fires.

move, resize: These events are dispatched when the component's location or dimensions are changed.

initialize, creationComplete: These events indicate when a com- ponent starts and finishes the creation process (including the creation of child components). If you have some ActionScript code that needs to run after all the child components have been created, be sure to use the creationComplete event (see Listing 3-10).

change: Many Flex components let the user change a selected value, such as the slider controls and the NumericStepper. Many of the con- trols in the framework will dispatch a change event to notify you that a change has occurred.

I n this part, we explore Flex Builder, the development tool you use to create Flex applications. Take a look around and get comfortable because Flex Builder is your new home. We begin by stepping you through the process of setting up Flex projects, tweaking settings, and running applications. Then we divide up Chapters 5 and 6 to cover the designer-oriented and the developer-oriented aspects of the tool. Regardless of whether you consider yourself a designer, developer, or ?devigner,? both chapters provide valuable information for creating Flex applications.

Chapter 4 Flex Builder: The Best Flex Development Tool In This Chapter Installing Flex Builder Understanding the different Flex Builder perspectives Creating and configuring Flex projects in Flex Builder Importing and exporting Flex projects Using the Help options to access sample code and Flex documentation T his chapter gets you up to speed on installing and using Flex Builder, the best development tool for working with Flex applications. Flex Builder is based on the Eclipse IDE (Integrated Development Environment), and it has different perspectives that allow you to develop, debug, and profile Flex applications. In this chapter, you can find out how to install Flex Builder and use Flex Builder for all of your Flex development needs. We cover how to create different types of Flex projects based on the type of application you're building; organize your Flex projects; build, clean, and run your projects; and edit project settings.

This chapter also explains how to access the help materials, such as sample code and Flex documentation, that are included with your Flex Builder instal- lation. After the details about how to set up and run a Flex project become second nature, you can develop your Flex projects with ease!

Developer-oriented features: Include a very robust ActionScript, MXML, and CSS code editor; a visual debugger; a visual profiler that allows you to profile performance and memory use; code refactoring so that code and many other tool capabilities.

Designer-oriented features: Include a Design view that allows you to visually assemble and edit Flex applications and components; and a CSS Design view that lets you visually style Flex applications and components.

Chapter 5 of this book covers the developer-oriented features of Flex Builder, and Chapter 6 focuses on the designer-oriented features. Look over both of those chapters for more specific information.

Often, each release of Flex is accompanied with a new release of Flex Builder so that the two technologies stay in sync. When a new feature is added into the Flex framework, the corresponding tooling support is usually added to Flex Builder so that developers can use the new feature when they author their Flex applications.

Flex Builder is an Eclipse-based IDE (Integrated Development Environment). You may already be familiar with Eclipse if you use the Eclipse IDE to write Java-based applications. Because Flex Builder is built atop Eclipse, you can use all the special plug-ins built for Eclipse in your Flex Builder tool. For exam- ple, many source-code management plug-ins allow you to check files in and out of your source-code repository directly from your Eclipse environment. You can easily install these plug-ins on top of your Flex Builder installation because Flex Builder is based on Eclipse. If you want to find out more about Eclipse, check out Eclipse For Dummies by Barry Burd (Wiley).

Installing Flex Builder You can install Flex Builder from the Flex product page at www.adobe.com/ go/flex_trial. You can install a 60-day trial version of Flex Builder and then at the end of the 60 days purchase the product for use permanently. To purchase Flex Builder directly, or at the conclusion of your trial, go to the online store at the Adobe Web site at www.adobe.com. Flex Builder is sup- ported on the Windows and Macintosh platforms, and installers for both supported platforms are included on the trial download page as well as the Adobe online store.

Chapter 4: Flex Builder: The Best Flex Development Tool 55

detail in a minute. After you've downloaded the installer, run through it to install Flex Builder as well as all of the source code for the Flex framework onto your computer.

A Linux version of Flex Builder is in active development. At the time of pub- lication, Flex Builder Linux is in a public alpha release, which you can find at Adobe's Labs site at http://labs.adobe.com/technologies/flex/ flexbuilder_linux/.

Flex Builder comes in two flavors for purchase (the trial download page lets you try out only Flex Builder Professional): Flex Builder Standard: This version includes the MXML, ActionScript, and CSS editors and the visual debugger.

Flex Builder Professional: This version includes everything contained in the Standard version, as well as the advanced data visualization librar- ies, such as the Flex charting components, the memory and performance profiler, and the Flex automated testing harness. Chapters 5 and 6 in this book describe these features and capabilities in more detail.

The trial version of Flex Builder is Flex Builder Professional, which includes capabilities such as the advanced data visualization components and the memory and performance profiler. Adobe offers the Professional version so that you can use the trial version as a way to evaluate which version of Flex Builder you want to actually purchase, Standard or Professional.

In addition to Flex Builder Standard and Flex Builder Professional, Flex Builder has two configuration flavors: Flex Builder Plug-In: Use this configuration version if you already use the Eclipse tool and want to install Flex Builder as an Eclipse plug-in atop your existing Eclipse setup. For example, if you already use Eclipse to develop Java applications, you may want to install the Flex Builder plug- in into your existing Eclipse environment.

Flex Builder Stand-Alone: This is a packaged installation of the Eclipse environment and Flex Builder functionality. This configuration is specifi- cally for building and deploying Flex and ActionScript applications. The Stand-Alone configuration has a much easier to use interface than the Flex Builder Plug-In version, because it's targeted directly toward developing Flex and ActionScript applications. Users new to ActionScript and Flex development should work with this configuration. All the examples and images in this book use the Stand-Alone configuration of Flex Builder.

Taking a look at the Flex Builder perspectives Flex Builder has a concept of perspectives in which a particular perspective consolidates the Flex Builder user interface to target a particular task. Flex Builder Standard has two perspectives ? Debugging and Developing ? and Flex Builder Professional includes a third perspective, Profiling. By using these perspectives, you can execute particular workflows or tasks more easily because each view targets a particular task. Figures 4-1 through 4-3 show the default user interface for the development, debugging, and profiling perspectives.

Flex Builder automatically changes the perspective when you do certain tasks. For example, when you create a new Flex project, the perspective automati- cally switches to the Flex Builder Development perspective. Similarly, when you set a breakpoint with the visual debugger and that breakpoint is hit, Flex Builder automatically switches to the Flex Builder Debugging perspective. To find out more about what a breakpoint is and how to use the visual debugger, jump over to Chapter 5, which discusses how to debug Flex applications.

Current perspective Navigator view Switch perspectives

Chapter 4: Flex Builder: The Best Flex Development Tool 57

Figure 4-2: The default view of Flex Builder's Debugging Figure 4-3: The default view of Flex Builder's Profiling perspective.

By default, Flex Builder prompts you about switching Flex Builder perspec- tives when you start a task that requires a perspective change. For example, hitting a breakpoint causes Flex Builder to open a dialog box, prompting you that it would like to switch to the Debugging perspective. Normally, you want to click Yes because the perspective change, which focuses the user interface more toward the task at hand, makes executing your task easier. If you don't want this confirmation dialog box to appear each time, select the Remember My Decision check box before you click Yes.

You can always see what perspective you're currently in by looking at the upper-right corner of your Flex Builder window. A button identifies the cur- rent perspective (refer to Figure 4-1), and you can click that button to switch to another perspective.

You can also manually switch perspectives by using the top-level Flex Builder menus: Choose Window?Perspective?Flex Debugging or Flex Development or Flex Profiling to switch perspectives.

Customizing perspective views When you change the view in a particular Flex Builder perspective, those changes become associated with that perspective; then when you switch back to that perspective later, those changes are reproduced. You can make many changes to the views in Flex Builder's user interface. You can resize views several ways: Minimize or maximize view by using the icons at the top of each view (refer to Figure 4-1).

Use the double-headed arrow cursor that appears when you hover over a view's border. When the double-headed arrow appears, click and drag to resize that particular view.

When you modify and resize different perspectives, you may want to go back to the default view for that perspective. You can reset the current perspective back to its size and layout defaults by choosing Window?Perspective?Reset Perspective. When you reset the perspective, you lose all the modifications that you made to that perspective's views.

Similarly, you can drag and drop views into different locations by hovering over the view's label and then dragging. The cursor changes into a folder icon to indicate you're moving the view. Flex Builder gives visual cues about where that view will be relocated when you drop it. In the example in Figure 4-4, we dragged and dropped the Outline view so that it's now next to the Navigator view.

Chapter 4: Flex Builder: The Best Flex Development Tool 59

Figure 4-4: We dragged and dropped the Outline view next to the Navigator view.

Creating Different Types of Projects in Flex Builder Flex Builder groups all the MXML, ActionScript, and CSS code files, as well as assets and other folders, into projects. A project is basically all the resources that comprise your application or component. Flex Builder lets you create different types of projects. The three main types of projects are Flex Project: You create this type of project when writing Flex applications. This is the most common type.

ActionScript Project: You create this type of project when you want to write an application that does not use the Flex framework but is instead an application written purely in ActionScript code.

Flex Library Project: Create this type of project when you want to write custom code that you'll distribute to other developers or link into other Flex projects.

To create one of these types of projects, choose File?New?Flex Project or ActionScript Project or Flex Library Project. In the following sections, we discuss each type of project in more detail.

Flex Projects Most often, you'll create Flex Projects, which is the type of project you create when you build most types of Flex applications. When you create a new Flex Project, you specify all the information that you need to configure and iden- tify that project. Information such as the project name, what type of data back-end the project uses, how the project should be built, and whether you want to target the application you're building for the Web or a computer desktop. When you choose File?New?Flex Project, the New Flex Project Wizard appears, ready to walk you through setting up the Flex Project (see Figure 4-5). Just follow these steps: 1. Specify the project name in the Project Name text field.

This name shows up in the Flex Navigator, which keeps track of all your projects.

Decide where you want all the source files, asset files, and ancillary information related to your project to live. Usually, you can just let Flex Builder use the default location.

Figure 4-5: The Flex Builder New Project Wizard walks you through the steps to create a new Flex project.

Chapter 4: Flex Builder: The Best Flex Development Tool 61

The application type determines whether you want to target the applica- tion that you're building for the Web or for the computer desktop. New in Flex 3 is the integration with Adobe AIR, a new technology that lets you use Flex technologies to build desktop applications. In Flex Builder 3, you can configure your Flex application to run as a Web application or as a desktop application. You can find out more about Adobe AIR at www.adobe.com/products/air.

You should make this choice based on which platform you are target- ing. By default, Flex Builder creates Flex projects that are targeted for the Web. If you change this option, Flex Builder uses the new option the next time you create a Flex project.

4. Choose the data back-end for your Flex application in the Server technology section.

By default, the None server option is selected. This setting often suffices when you're building Flex applications that use the Flex RPC libraries, such as the WebService MXML tag or HTTPService MXML tag. By selecting the appropriate option from the Application Server Type drop-down list, you can also target an ASP.NET, J2EE, ColdFusion, or PHP back-end. You select the J2EE option when you build a Flex application that targets LiveCycle Data Services. LiveCycle Data Services is an Adobe technology that includes many of the high-end, enterprise level data features large projects desire. You can find out more about LiveCycle Data Services on the Adobe Web site.

6. Specify the folder in which you want to place the output for your Flex application. Then click Next.

By default, the output is put in a folder called bin-debug at the root of your Flex project. You can almost always use this default but may choose to change the folder name to follow your own coding conventions.

After you click Next, the next step appears, in which you specify the build paths for your Flex application, as shown in Figure 4-6.

Build paths specify the location of external source and library files. By default, all the controls and components that comprise the Flex frame- work are specified in the Library pane. So, right out of the box, a new Flex project is set up to build Flex applications. Most of the time, when you start building and creating Flex applications, you don't need to add any additional source files to the build path.

Figure 4-6: The Flex Builder New Project Wizard prompts you for modifi- cations to the build path.

8. Click Finish to create a Flex project that has all the settings you've specified in the New Project Wizard.

After you create the project, it appears in the Flex Builder Navigator view. You use the Navigator view to delete projects or modify the properties of existing Flex projects. The root MXML file for the new project opens auto- matically in Flex Builder once the project has been created, and this file is usually the entry point into your Flex application and where you begin your application development. For example, if you create a new project called HelloWorld, HelloWorld.mxml is the root MXML application for the project, and a skeleton MXML file opens in the MXML editor. Voilà, you're ready to go! If the Flex project name has a space or hyphen in it, the root MXML file that is auto-created by Flex Builder is named main.mxml. If the project doesn't have a space or hyphen in it, Flex Builder names the root MXML file the same name as the project.

Chapter 4: Flex Builder: The Best Flex Development Tool 63

ActionScript Projects ActionScript Projects are applications that don't use the Flex Framework (and thus MXML) and, instead, are built purely with ActionScript code and the libraries offered natively by the Flash Player. Because Flex Builder has a very powerful ActionScript code editor and debugger, Flex Builder is the perfect tool for building ActionScript-only applications.

To create a new ActionScript project, choose File?New?ActionScript. Then follow these steps to use the New ActionScript Project Wizard (shown in Figure 4-7) to create your project:

Figure 4-7: The Flex Builder New Project Wizard walks you through creating a new ActionScript project.

2. Specify the location for the project's code files, asset files, and all other source material in the Project Contents section.

3. Choose which version of the Flex framework the application should target in the Flex SDK Version section.

discuss this feature in more detail in the ?Targeting different versions of the Flex Software Development Kit (SDK)? section, later in this chapter. By default, Flex Builder always creates a new application that targets the latest released version of the Flex framework. Certain prior versions of the Flex framework source code are shipped with Flex Builder, and your application can target these prior versions. Simply select the Use a Specific SDK radio button and select the desired version of the Flex framework in the version drop-down list.

Flex opens the Build Paths pane in the New ActionScript Project Wizard, shown in Figure 4-8.

In this window, you can specify where external source files or libraries are located and include them into the source path of your application so that your application can access that code. Often, you can use the default settings because Flex Builder already adds the Flex Framework source code into the build path so that you can access all the classes and code in the various Flex Framework libraries.

Figure 4-8: In this wizard pane, you can edit the build path to include other source- code libraries.

Chapter 4: Flex Builder: The Best Flex Development Tool 65

The new ActionScript project is created and appears in the Flex Navigator view. You use this entry in the Flex Navigator to edit the proj- ect's settings or delete the project.

After you create the project, the root ActionScript file opens in the ActionScript code editor automatically. This root ActionScript file is usually the entry point into your application, and it's the file that Flex Builder compiles when creating your application's output.

Flex Library Projects The final type of project that you can create is a Flex Library Project. You use a Flex Library Project to create custom code libraries that you link into other Flex applications or distribute to other developers. A Flex Library Project produces SWC files, which are compressed files containing ActionScript and MXML code. Flex Library Projects are an advanced topic, and you can consult the Flex Builder documentation included with your Flex Builder installation for more information on configuring Flex Library projects. The ?Accessing Flex Builder Help Materials? section, later in this chapter, describes how you can access Flex Builder documentation directly within Flex Builder.

Organizing and Editing Your Projects You can organize the source files related to your project however you want, but Flex Builder automatically uses some organizational methods to help you maintain your project. By default, Flex Builder puts source files such as MXML, AS, and CSS files into the src folder in the project directory. The out- putted SWF and HTML files that represent your application are put in the bin- debug folder that lives in the project directory.

You can create new folders for organizing your source files. Usually, you want to create these new folders as subdirectories to the src folder. For example, Flex application developers often create a folder called images or imgs to hold their visual assets, such as .jpg, .gif or .png files.

To create a new folder, follow these steps: 1. Locate the directory in the Flex Navigator view that you want the new folder to live in and then right-click that directory.

A context menu opens, containing options that let you modify the project properties and source files.

When you choose New from the context menu, you can create other ele- ments, in addition to folders. For example, you can create a new MXML application, MXML component, ActionScript class, or a plain file.

3. Specify the name and location of the new folder Whenever you need to add any new document to your project, right-click the project and select the New option in the context menu or select which document you want to create from the top-level menu options (File?New). The Flex Builder wizards walk you through naming and setting properties on these new documents.

Figure 4-9: You can right-click projects in the Flex Navigator to create new files or folders.

Chapter 4: Flex Builder: The Best Flex Development Tool 67

Editing existing project settings You can edit project properties such as build path and output folders on an existing project very easily by using the Flex Navigator. Simply right-click the project name in the Flex Navigator and select Properties from the context menu that appears. A Properties dialog box, similar to Figure 4-10, appears. Select a listing from the left pane to edit that particular property or setting.

For example, if you want to create a Flex application that's accessibility enabled ? meaning a Flex application that an assistive screen reader can read ? open the Properties dialog box (shown in Figure 4-10), select Flex Compiler, and select the Generate Accessible SWF File check box.

If you tweak your project properties too much and want to go back to Flex Builder's project defaults, simply click the Restore Defaults button at the bottom of the project Properties dialog box. All the settings on that particular project restore back to their defaults.

In addition to the Flex Navigator, you can use the top-level Flex Builder menus to open the project Properties dialog box. Simply select the project in the Flex Navigator view and choose File?Properties.

Figure 4-10: The Properties dialog box lets you edit the existing project's properties.

Deleting projects To delete a project, right-click the project in the Flex Navigator view and select Delete from the context menu that appears. The Confirm Project Delete dialog box opens. You can choose one of the following options to delete the project: Delete the project from the Flex Navigator view and keep all the project's content. If you select this option, you can always import the project back into Flex Builder. To find out more about importing Flex Builder projects, check out the section ?Importing and Exporting Existing Flex Builder Projects,? later in this chapter.

Delete the project, as well as all its contents, meaning any source files that comprise that project.

Be careful when choosing to delete all of a project's content because you can't restore it after deletion. By default, the Do Not Delete Contents option is selected.

Targeting different versions of the Flex Software Development Kit (SDK) Flex Builder 3 includes a new feature that allows you to choose which version of the Flex SDK (Software Development Kit) you want your Flex or ActionScript project to target. The Flex SDK is basically all of the code libraries and the MXML compiler that is needed to create and compile a Flex application.

When new versions of the Flex SDK are released, Flex Builder installs the newest version as well as some prior versions of the Flex SDK during the installation process. That way, Flex Builder lets you target prior versions of the Flex SDK when you build your Flex application. By default, Flex Builder creates projects that target the latest version of Flex. You may choose to target an older Flex SDK, for example, when a new version of Flex Builder comes out and you import one of your pre-existing projects. For example, you may want to ensure that the old project targets the older version of the Flex framework if you don't want to update your project's source code to work with the newer version of the Flex SDK You can set or edit the targeted SDK project property by following these steps: 1. Right-click the project's name in the Flex Navigator and select Properties from the context menu that appears.

2. In the left pane of the Properties dialog box, select the Flex Compiler option.

Chapter 4: Flex Builder: The Best Flex Development Tool 69

In the Flex SDK Version section on the right side of the dialog box, the Use Default SDK option is selected, as shown earlier in Figure 4-10. That option also displays what the default SDK is (it's often the latest version of the Flex SDK like Flex 3).

3. To choose which SDK version you want the project to target, select the Use a Specific SDK radio button. Then from the SDK drop-down list, select which Flex version you want to target.

Importing and Exporting Existing Flex Builder Projects Flex Builder lets you import an existing project or export a project as an archive file. You may find this feature helpful in situations in which Flex proj- ects are archived in a source control repository for sharing code among team members.

A source control repository (also known as revision control software) is a piece of software that allows for the management and organization of multiple ver- sions of software between team members. CVS, Perforce, and SVN are all common types of source control repository software.

You can simply import projects from a source control repository that already have their project settings configured. This is because as you create a proj- ect and edit its properties, Flex Builder creates a file representing that project and its configuration and saves the file in the project directory. You can import the project directory into Flex Builder, and the project can be created and configured based on the information in that project file. If you're working on a team that has multiple developers working on the same projects, these project- importing capabilities can be very handy for quickly setting up complex projects. Similarly, you can use the export project options to export a project as a Zip file and then easily share the project with other developers who use Flex Builder.

Importing a project The steps to import an existing project are very straightforward: 1. Choose File?Import?Flex Project.

Decide whether you want to import the project from an existing archive file ? that is, a Zip file ? or from a folder on your file system that con- tains all the project source files and a file capturing the project configurations 2. Click the Browse buttons for whichever option describes the project that you want to import and select the Zip file or folder that encom- passes your project.

3. (Optional) To change the location where you want the files to be imported, un-check the Use Default Location option and, in the Folder text field, specify the location in your file system.

Figure 4-11: Flex Builder's Import Wizard lets you import existing projects from an archive Zip file or exist- ing source code on your file system.

Exporting a project as an archive Flex Builder offers a simple wizard that you can use to export an existing project into an archive (that is, a Zip) file. Just follow these steps: 1. Select the project in the Flex Navigator view. Then, choose File? Export?Flex Project Archive.

3. Use the Browse button to choose a location where you want to place your project's archive Zip file.

This Zip file contains all the source code and assets that comprise the Flex application.

Chapter 4: Flex Builder: The Best Flex Development Tool 71

Figure 4-12: Flex Builder's Export Wizard lets you export your proj- ect into an archive Zip file.

Voilà, your project exports into a handy Zip file that you can send to other developers on your team!

Running and Releasing Your Projects Flex Builder allows you to build your project ? that is, compile the project into the appropriate end result ? for use in a debugging session or for releasing to your end users. The most common build task is for you to enable the Build Automatically option, which means that the project is built continually, and Flex Builder reports errors in the current state of your project in the Problems view in real time. By default, the Build Automatically option is not set because this capability can take a long time, depending on the size of your project.

Building and cleaning your projects To enable the Build Automatically option, choose Project?Build Automatically from the menu bar. When you write code in your project with Build Automatically enabled, Flex Builder alerts you of errors, such as compi- lation errors, in the Flex Builder Problems view. For example, in Figure 4-13, the Problems view points out an error in which a component id is inaccurate.

too long to build and analyze the current state of your project, you can disable Build Automatically to gain a performance boost.

If you don't enable Build Automatically, you can build your applications by selecting the appropriate build options in the top-level Project menu. You can choose to build all your projects, a single project, or a set of projects.

Sometimes, you may want to clean your projects before building to ensure that all the changes have been analyzed and the prior build output is cleared. To clean your projects, choose Project?Clean. The Clean dialog box opens, in which you can choose to clean all the projects in your workspace or a specific project. Get into the habit of cleaning your projects so that you can ensure they stay in up-to-date shape.

Run Figure 4-13: When you enable Build Auto- matically, compilation and build problems appear in the Flex Builder Problems view.

Running your projects To run your project ? that is, to output the project into its runable form, such as loading a SWF application in a Web browser ? click the Run icon, shown in Figure 4-13. Flex then compiles the project and opens the applica- tion in a browser window so that you can view it. If Flex encounters compila- tion problems, those problems appear in the Problems view, and you need to fix them before you can run the application.

Chapter 4: Flex Builder: The Best Flex Development Tool 73

To find out how to debug your application, refer to Chapter 5 for information on using Flex Builder's visual debugger.

Releasing your projects After you develop your projects to satisfactory form, you need to get all the files built in a way that is appropriate for the application to be released to its end users. Flex Builder gives you the option to export a project into a release version, in which the project does not include any bloat-inducing materials, such as debug information.

To export a release version of your application by using the Export Release Build Wizard, follow these steps: 1. Choose File?Export?Release Build.

2. From the Project drop-down list, select the project that you want to export, and from the Application drop-down list, select the root MXML or ActionScript file for that project.

Figure 4-14: Use the Export Release Build Wizard to create a release ver- sion of your project.

3. (Optional) Check the Enable View Source check box if you want to build a release version of your application that allows users to right- click in your running application and view the source files and code (including ActionScript, MXML, and CSS files) that comprise your application.

By default, this option is unchecked, but if it's okay to introduce an ele- ment of transparency in your application (that is, let users see the code behind the running application), go ahead and select the Enable View Source option.

4. In the last section of the dialog box, browse to a location in the file system where you want to write the release version files.

You now have an export-worthy version of your project that you can upload to your production servers and share with the world!

Accessing Flex Builder Help Materials Flex and Flex Builder documentation that you can use to understand features and quickly get help when you're working on your projects are built into Flex Builder. You can use most of these options through Flex Builder's top-level Help menu. Here are some of the options available on this menu: Help Contents: View help materials in a separate window.

Report a Bug: Access the public, online Flex bug-base, in which you can enter new bugs, and watch and vote on existing bugs in the Flex frame- work and Flex Builder products. The online Flex bug base is located at http://bugs.adobe.com/flex.

Flex Start Page: Return to Flex Builder's start page, which has all sorts of useful information and a tutorial to get you up and running building simple Flex projects.

Chapter 5 Introducing Flex Builder for Developers In This Chapter Understanding the composition of an MXML file Improving productivity with a few Flex Builder tricks Debugging and profiling your application Refactoring your code I n this chapter, we cover the Flex Builder features that you will specifically use for writing code, debugging, and optimizing your applications. This chapter covers the nuts and bolts of how to build and run Flex applications; if you're interested in finding out how to make your applications look pretty, page ahead to Chapter 6.

This chapter starts off by breaking down the different parts of an MXML file and explaining how you can combine MXML code, ActionScript code, and style blocks together and make them all play nice. Then you discover a few Flex Builder tips that will make you glad you purchased Flex Builder. In the last few sections of this chapter, you find out about debugging and profiling with Flex Builder's built-in tools.

These three elements can be used interchangeably within a single file. The example in Listing 5-1 is a small Flex application that contains all three indi- vidual pieces.

Listing 5-1: A Typical MXML Application with MXML Markup and Style and Script Blocks

?4 .redButton { text-roll-over-color: #FFFF00;

} ? 11

? 13

private function clickHandler(event:Event):void { } ]]> ? 22

? 25

? 27

The following list takes a closer look at Listing 5-1: ? 4 On Lines 4 through 11, you create an block that contains a CSS style. In this example, you create a style named redButton that sets the fill-colors and fill-alphas styles, which create an opaque red gradient background fill. You also set the color and text-rollover-color styles, which affect the color of the text on the Button that will apply this style. (See the ?Introducing the tag? section, later in this chapter, for more on CSS.) ? 13 Lines 13?22 define a block that contains an ActionScript function. Anything within the block must be ActionScript code; you cannot mix and match ActionScript and MXML within the block. In this example, you create a function that runs when the user clicks the Button defined in this Application.

Chapter 5: Introducing Flex Builder for Developers 77 ? 24 After the block, you add the rest of the MXML tags that create this Application. In this simple example, you add a single that will create a clickable button with a label that says Click Me. You reference the ActionScript clickHandler function that you defined previously in the block (Lines 13?22).

? 25 You set the styleName of this Button to redButton, which ref- erences the CSS style that you created in the block (Lines 4?11). This gives the Button a red gradient background.

Including ActionScript with the tag You can create simple Flex applications with just MXML, but to make an application do something, you need to write some ActionScript. The good news is that MXML and ActionScript can coexist in the same file, so you can use the full power of ActionScript with the declarative markup of MXML.

The block in Listing 5-2 shows how to include ActionScript within MXML. The block is required, but should get automatically inserted by Flex Builder when you type . You can declare variables and methods within the block, and then you can reference those variables and meth- ods in your MXML component tags.

Listing 5-2: Combining ActionScript with MXML Markup

private function incrementCounter():void { } private function decrementCounter():void { myCounter--;

Listing 5-2 (continued)

Listing 5-2 shows how to declare a variable ? myCounter ? in ActionScript that then gets referenced in MXML. In this example, you use data binding to populate the text property of the component. Data bind- ing is a powerful feature of MXML that allows you to reference ActionScript variables within MXML markup. The curly braces that you see around the myCounter variable in Listing 5-2 show data binding in action. At runtime, the contents of the text property will always be updated to include the latest value of myCounter whenever it changes. For an in-depth look at data binding, head over to Chapter 12.

This listing also shows how to invoke ActionScript functions in response to user interaction with components defined in MXML. You add a few tags to your application and use the click event on the but- tons to call the functions you defined in the block.

Introducing the tag Flex supports styling using Cascading Style Sheets (CSS), similar to how CSS is used in HTML pages. CSS lets you define sets of styles that will affect the visual look and feel of your application. You can define styles for specific components or use custom style names, and these styles will affect every- thing from border color to font size. However, you should note that CSS styl- ing in Flex applications isn't the same as CSS styling in HTML. Flex supports only a subset of the full functionality of CSS, and the style names you may be familiar with in HTML CSS aren't the same. For example, CSS in HTML allows nested (cascading) styles, but nested styles aren't allowed in Flex. This means that Flex supports styling in a similar way as CSS, but without the cas- cading part. Think of the styling approach in Flex as similar to CSS, but not real CSS.

You can style your Flex applications in four ways: Use an external CSS file and point to that file by setting the source property of a tag.

Chapter 5: Introducing Flex Builder for Developers 79 Set styles through ActionScript by calling the setStyle(styleName, value) method on a specific component.

Listing 5-1 uses the first method to create the red button style. For more detailed information about styling, refer to Chapter 18.

Developer Tips and Tricks You don't technically need Flex Builder in order to create Flex applications. If you're inclined, you can download the free (and open source) Flex SDK, use a text editor to write your code, and compile the code with the command-line compiler. So why would you shell out the cash to purchase Flex Builder? A number of its features dramatically improve your productivity while building Flex applications. We cover two of the most important features, the Debugger and the Profiler, later in this chapter. This section focuses on a few other helpful features that Flex Builder provides.

Get the hint: Code hinting Flex Builder provides code hinting while you type, and after you experience code hinting, you'll cry if you ever have to go back to an editor without it. Code hinting, or content assistance, shows a drop-down list of possible options to complete the line you're typing. This feature works while you're editing both MXML and ActionScript.

To understand the power of code hinting, create a new Flex application and add a simple button to your application by typing

At any point while you're typing, you can use the arrow keys to scroll through the applicable options. After you get the hang of using code hinting, you find that have to type only the first few letters of the properties you want and then quickly select the appropriate property from the list.

When you're editing an MXML tag, code hinting is automatically invoked when you type the space character. You can manually invoke code hinting at any time by pressing the key combination Ctrl+spacebar. We have become so dependent on code hinting that we inadvertently press Ctrl+spacebar on normal Web page forms, in the hope that code hinting will automatically com- plete the form for use. Learn to use the Ctrl+spacebar shortcut well, and it will become your best friend.

When you first use Flex, you may have difficulty keeping track of all the names of the properties available for each component. You can use the online Flex SDK documentation to look up a full list of properties, but often the fastest way is to invoke code hinting on an MXML tag and browse through the list. In fact, if you simply type the beginning of an MXML tag in your application by typing <, the full list of all components you can use in your application pop ups, which is useful before you memorize the names of the full Flex SDK com- ponent set (see Figure 5-2).

Figure 5-2: Using code hinting to browse all available compo- nents.

Code hinting also works when you edit ActionScript code. While editing ActionScript, you can use the same Ctrl+spacebar keyboard shortcut to manually invoke code hinting where it's available. As you type, you notice that code hinting is automatically displayed at various points ? for example, whenever you type a period after a variable name to access properties of that variable.

Figure 5-3 shows the code hinting that appears in ActionScript as you type button.s, which lists all properties, styles, events, and effects available on the button variable that begin with the letter s.

Chapter 5: Introducing Flex Builder for Developers 81 Exploring the Flex SDK source code You can use the Ctrl+click approach to jump is large and full of useful information, but you to the source file of any class in the Flex SDK, must have a fairly advanced knowledge of Flex If you Crl+click a class that's part of the Flex get a solid understanding of how Flex works, framework, Flex Builder loads the source for you can start digging into the internal workings that particular class. This action lets you dive of the framework by analyzing the source code into the details of how the Adobe Flex team of the framework itself. For now, just know that built the Flex SDK. Try not to get overwhelmed the code is available to you if you want to dig in the first time: The source code for the Flex SDK and figure out how Adobe did something.

not just to the source files you have created. to properly understand this resource. After you

Figure 5-3: Using code hinting while typing ActionScript Going straight to the source code Another powerful advantage of using Flex Builder is that you can jump into the source code for any MXML tag or ActionScript class you see in your application. If you move the mouse cursor over any MXML tag while holding down the Ctrl key (or the Ô key, if you're a Mac user), an underline appears under the class name of the MXML tag, as shown in Figure 5-4. Clicking this tag while holding down the Ctrl key opens the source file for that class, which can be useful when your application is divided into multiple MXML compo- nents and you reference one MXML file within another.

Using automatic builds To run your Flex application, you need to build a compiled SWF file from the source MXML and ActionScript files. You have two build options: Automatic: You can turn automatic builds on or off by toggling the Project?Build Automatically menu item, shown in Figure 5-5. If auto- matic builds are turned on, each time you save changes to your source files, the compiler rebuilds your application.

Manual: If you turn off automatic builds, you have to perform manual builds. The primary reason for disabling automatic builds is to improve the performance of Flex Builder. If you notice Flex Builder running slug- gishly whenever you save a file, you might want to try turning off auto- matic builds. For more on building your project, see Chapter 4.

Figure 5-5: The Project menu with its build Organizing import statements When you write ActionScript code, you need to have, at the top of your class, a block of import statements that let the compiler know which external classes you reference. Flex Builder is good at automatically adding the import state- ments to the top of your class, although if you aren't using the content assis- tance features fully, you may have to write some import statements by hand. At the top of your class, you see lines that look like this:

Chapter 5: Introducing Flex Builder for Developers 83 These import statements tell the compiler where to find all the classes that you use somewhere in your code. As you write more and more code, the number of import statements grows. If you remove chunks of code and you no longer reference certain classes, extraneous import statements are left in your code. Luckily, Flex Builder can automatically organize your import state- ments, which removes any unused imports and orders your imports by pack- age name and in alphabetical order.

Flex Builder can be set to always keep your import statements organized, or you can manually run the Organize Imports command whenever you like. The default Flex Builder installation has automatic import organization turned on. To modify the import organization properties, choose Window?Preferences? Flex?Editors?ActionScript Code to open the Preferences panel, as shown in Figure 5-6.

Figure 5-6: Flex Builder import organization If Flex Builder is set to automatically organize your import statements, then it will reorganize the code in the previous example to produce the following lines:

Notice that the import statements are now in alphabetical order based on the full package name, and an extra white space line is inserted between blocks of imports from different base packages. If you have Flex Builder set to not automatically organize your import statements and they seem clut- tered and unorganized, try running the Organize Imports command manu- ally by choosing Source?Organize Imports.

Import organization is available only if you're editing a pure ActionScript file. If you're editing an MXML file that contains an block with ActionScript code, you have to manually organize your own import statements.

Squashing Bugs with the Visual Debugger Debugging code is an integral part of writing software applications. Nobody writes bug-free code, so having a solid debugging tool to help track down those pesky bugs is a must. If you come from a Flash development back- ground, you have probably had the unpleasant experience of writing ActionScript code in the Flash IDE and using millions of trace() statements throughout your code as the primary means of debugging. Thankfully, Flex Builder provides a full-fledged debugger that's essential for powerful applica- tion development.

Launching the debugging perspective To begin debugging your application, run the debug version of the compiled SWF. To launch debugging, select your main application file, right-click, and choose Debug As?Flex Application. This command switches Flex Builder from the Flex Development perspective to the Flex Debugging perspective, shown in Figure 5-7.

Using breakpoints to step through code An essential debugging technique involves adding breakpoints to your code. Breakpoints are markers at specific lines in your source code that pause code execution. After a breakpoint is reached, you can step into the code, inspect variables, and step through the code line by line to understand exactly what's happening as the code executes.

You can add a breakpoint to your code in two ways: Place the cursor at the line you want in your code and choose Run?Toggle Breakpoint from the Flex Builder menu.

After a breakpoint is added, you see a round dot icon next to the line number, indicating that the breakpoint has been added (see Figure 5-8).

Chapter 5: Introducing Flex Builder for Developers 85 Figure 5-7: The Flex Debugging perspective.

Figure 5-8: A break- point on When you run the application in Debug mode, it pauses when it reaches a breakpoint, and at that point you can use the debug controls to step through the code. The debugging control bar is shown in Figure 5-9.

You can use the first few buttons on the toolbar shown in Figure 5-9 to con- trol the debugging session by resuming code execution or terminating the debugging session. If you press the play button to resume code execution, the application continues to run until the next breakpoint is reached. The fairly self-explanatory stop button ends your debugging session.

Step Into Step Over Play Stop Step Return Figure 5-9: The debugging control bar.

Use the three buttons with the arrow icons (refer to Figure 5-9) to step through your code line by line: Step Into: The first button in this set, the Step Into button, steps into any functions in the current line of code. If the debugger is paused on a line that contains calls to another function, which might be contained in a separate class, clicking the Step Into button loads that function (even if it is defined in a different class) and continues debugging.

Step Over: Alternatively, you may want to stay in the function you're debugging and not jump around into each of the functions that are refer- enced. In this case, you can use the Step Over button to ?step over? the function and continue debugging on the next line.

Step Return: The third button, Step Return, jumps out of the current function and pauses the debugger wherever that function returns. You then jump to wherever that function was called and continue debugging from there.

Debugging a Flex application consists of stepping through much of the code line by line to identify the exact location of bugs. You will become quite famil- iar with setting breakpoints and stepping into, out of, and over your source code.

Inspecting variables Stepping through lines of code on its own isn't incredibly useful, but inspect- ing the state of variables while debugging certainly is. During the debugging process, the Variables panel (shown in Figure 5-10) contains a list of all popu- lated variables and their values.

The example in Figure 5-10 sets a breakpoint in buttonClickHandler, after the values for username and password have been assigned. You can then view the values in the Variables panel and ensure that they are in fact valid values before they get sent to the Web service later in the function.

Chapter 5: Introducing Flex Builder for Developers 87 Figure 5-10: The Variables panel.

Profiling Your Application Flex applications can produce stunning visual effects and load tremendous amounts of data, but an inherent danger accompanies that power. Flex appli- cations also have the potential to consume massive amounts of memory and processing power on the user's computer. Building a large and impressive Flex application is a constant balancing act in which you have to always be aware of the cost, in terms of RAM use and CPU performance, for these rich experiences.

Of all the new features added to version 3 of Flex Builder, perhaps the most useful is the Flex Profiler, which lets you monitor your application's perfor- mance and dig in to identify bottlenecks and memory leaks. Writing high- performance, scalable Flex applications is no easy task, but the Flex Profiler takes much of the guesswork out of application optimization.

In this section, we give you an overview of using the Flex Profiler, for both memory management and performance profiling. For more detailed per- formance tips and further discussion of using the Flex Profiler, refer to the bonus chapter titled ?Optimizing Your Flex Applications,? available for down- loading at www.dummies.com/go/adobeflexfd.

The Flex Profiler is available only if you purchased the Professional version of Flex Builder 3. In this section, we assume that you have purchased Flex Builder Pro. If you have the trial version of Flex Builder, you can test the fea- tures of the Profiler that we discuss here during your trial period.

large. As all these objects accumulate in memory, the amount of RAM needed to run your application increases.

If the number of objects in memory continues rising, eventually your applica- tion becomes sluggish and unresponsive and might even lock up the user's computer. As your application runs, the Garbage Collector continuously moni- tors the memory use of your application and ensures that any objects you need stay in memory and that all unneeded objects are dumped. By dumping unneeded objects, the Garbage Collector frees up memory to keep your appli- cation running smoothly.

To determine which objects should stay in memory and which ones can be collected, the Garbage Collector checks all objects for references to the object in other parts of the application. If a reference to the object is found, the object cannot be garbage-collected because that would make it unavail- able and the other part of your application that needs it would have a prob- lem accessing it.

You can use a few tips and tricks to help ensure that you're freeing up refer- ences to objects that you want garbage-collected. See the bonus chapter (?Optimizing Your Flex Applications?) for a discussion of some of these hints.

You cannot predict when the Garbage Collector will sweep through and col- lect the trash. How often it runs is determined by a variety of factors, includ- ing the memory limitations placed on Flash Player by the browser in which your application is running. The garbage-collection process might run more often in one browser than in another, or more often on one user's computer than on another. Because the Garbage Collector tries to run only when neces- sary, your Flex application eats up as much memory as it wants, to a certain point ? when Flash Player decides that it's time for a little housecleaning.

Profiling memory use When you're optimizing your Flex application, you should focus on two distinct areas: memory usage and CPU performance. Profiling memory use involves keeping track of all objects held in memory and identifying memory leaks. A memory leak occurs when an object that's no longer needed contin- ues to be held in memory. In this section, we cover profiling memory usage, but for in-depth coverage of identifying and preventing memory leaks, refer to the bonus chapter.

If you want to initialize the Profiler, you launch your application in a slightly different way. You can either right-click a main application MXML file and choose Profile As?Flex Application or choose Run?Profile from the main Flex Builder menu, shown in Figure 5-11.

Chapter 5: Introducing Flex Builder for Developers 89 Figure 5-11: Launching the Flex Profiler.

Before launching the profiling session, you can specify which profiling options you want to enable. The properties dialog box shown in Figure 5-12 lets you enable or disable different options for memory and performance profiling.

The Enable Memory Profiling check box controls whether the Profiler keeps track of memory statistics. If you deselect this box, you can still profile the performance of your application, but no memory details will be available. Within memory profiling, you have two configuration options: Watch Live Memory Data box: If you select this check box, a list of all Otherwise, you have to take a memory snapshot when you want to see the objects that are in memory.

Generate Object Allocation Stack Traces: This check box controls whether the Flex Profiler keeps track of where in your source code each object in memory was created. If you select this check box, you can inspect each individual object and see exactly where the object was cre- ated, which can be helpful for tracking down memory leaks.

The Watch Live Memory Data and Generate Object Allocation Stack Traces options both provide useful information while profiling your application but require significant resources on your computer. If you have a powerful com- puter, you can probably select both options; if you find the performance of the Profiler to be an issue, however, try disabling them. You don't create a complete picture without them, but sometimes the Flex Profiler can be a resource hog.

After you begin profiling your application, Flex Builder switches into the Profiling perspective, as shown in Figure 5-13. The Profiling perspective is divided into three main parts: the profiling session controls in the upper-left area, the Memory Usage chart in the upper-right area, and the Live Objects list along the bottom.

Profiling session controls Memory Usage chart

Chapter 5: Introducing Flex Builder for Developers 91 Inspecting live objects If you leave the Watch Live Memory Data check box selected in the Profiler's option panel, the Profiling perspective shows a list of all objects in memory as your application runs. This list can be sorted and filtered in real time and can help you inspect object creation and collection as it happens.

Figure 5-14 shows some sample output in the Live Objects panel. The list shows unique entries for each class and displays the number of instances and the amount of memory that was allocated.

Take Memory Snapshot Filters Figure 5-14: Inspecting live objects in memory.

Here's a closer look at the individual columns in the Live Objects panel: Class column and Package column: The first two columns, Class and Package, identify the class so that you can track down exactly which objects you're looking at. By default, the Flex Profiler filters out the Flex and Flash packages (all classes under the mx.* or flash.* package structure). These default filters can be useful if you want to focus on custom classes, but sometimes you want to include the classes from the Flex framework to see how they're affecting memory usage. You can change the filters by clicking the Filters icon (refer to Figure 5-14).

In Figure 5-14, we removed the mx.*.* filter so that we can see the Flex classes that are taking up memory.

Cumulative Instances column and Instances column: The next two col- umns, Cumulative Instances and Instances, tell you how many objects of a given class have been created: · Cumulative Instances: Refers to the total number of objects that have been created since the application started · Instances: Displays the number of instances that are live in memory If the count in the Cumulative Instances column is higher than the count in the Instances column, you know that some of the objects that were created were garbage-collected.

If you compare the numbers in the Cumulative Instances column and the Instances column shown in Figure 5-14, you can see that the applica- tion created 92 total instances of the Image class and that only 5 remain in memory. The other 87 instances of the Image class, therefore, were garbage-collected.

Cumulative Memory column and Memory column: The next two col- umns, Cumulative Memory and Memory, indicate how much total memory has been allocated for each class and how much memory each class is occupying. If you look at the corresponding numbers in Figure 5-14, you can see that the 92 instances of the Image class occupied a combined 112,608 bytes. The more important number in this view, however, is in the Memory column, which indicates that the 5 Image objects that remain in memory are occupying a total of 6,120 bytes. This number contributes to the total memory footprint of your application.

If your application is correctly freeing objects for garbage collection, the general trend you see is that the numbers in the Cumulative Instances and Cumulative Memory columns keep increasing while the values in the Instances and the Memory columns rise and fall, indicating that objects are being cre- ated and garbage-collected correctly. A common sign of a memory leak is if the numbers in the Incidents column and Memory column continue to increase but never decrease.

Taking memory snapshots Inspecting live memory allocation in your application can be incredibly useful, but sometimes you want to compare the amount of memory used in your application at different stages. At any point while the Flex Profiler is running, you can take a memory snapshot, which captures the memory allo- cation data at the time you take the snapshot and saves it so that you can analyze it later. To take a snapshot, click the Take Memory Snapshot button, as shown in Figure 5-14.

When you take a memory snapshot, a new snapshot entry is added to the profiling session, as shown in Figure 5-15. You can select a snapshot by double-clicking the entry, which loads the snapshot details into a new panel.

Capture Performance Snapshot Finding Loitering Objects Figure 5-15: Multiple memory snapshots.

Chapter 5: Introducing Flex Builder for Developers 93 Each memory snapshot contains information that's similar to the information shown in the Live Objects panel, except that it contains only the information about the in-memory objects at that particular moment.

No loitering! If you have two memory snapshots, you can compare them to find loitering objects, which have been left in memory and might indicate memory leaks. To view a list of loitering objects, you can select two memory snapshots in the list and compare them by clicking the Find Loitering Objects button (refer to Figure 5-15).

If you compare two memory snapshots and find an unexpected list of loiter- ing objects that are taking up memory, it might be an indication of a memory leak in your application.

Because the Garbage Collector runs intermittently, a certain number of loiter- ing objects remain in memory between garbage-collection cycles. So, finding a few loitering objects isn't a concrete indication of a memory leak ? you may have just caught the Garbage Collector between cycles. While you are running the Flex Profiler, you can force the Garbage Collector to run by clicking the Run Garbage Collector button. (You cannot force the Garbage Collector to run unless you are using the Flex Profiler.) To track down why loitering object cannot be garbage-collected, you can inspect the individual object instances and check the references to those objects.

Inspecting object references When you view a list of objects in memory, either while inspecting a memory snapshot or a list of loitering objects, you can double-click a specific entry to view the object references for that class. When you double-click an entry, a new Object References panel loads, as shown in Figure 5-16.

In Figure 5-16, you're inspecting the references to Image objects. You can see two instances of the Image class listed in the left pane. In this list, you see not only the individual instances but also how many references to these objects are in the application. The listing shown in Figure 5-16 indicates that the first Image instance in the list has 13 references in the application. The second Image object, however, has no references, which indicates that it will be garbage-collected in the next pass of the Garbage Collector.

The right pane shows where in the code that particular object was created. Note that this information is available only if you turned on the Generate Object Allocation Stack Traces option when you launched the Flex Profiler. You can use this information to trace the sequence of steps that created a particular object.

If external references to an object exist, the Garbage Collector cannot col- lect that object. So, if you examine all references to loitering objects, you can determine which references are keeping the object from being collected.

A picture is worth a thousand words The upper-right panel in the Profiler perspective is a live memory chart that shows the memory usage of your application during its lifetime (refer to Figure 5-13). You can gain a great deal of insight into your application's memory usage by checking image snapshots, but viewing the graph of memory allocation sometimes makes memory problems jump out at you.

Figure 5-17 shows a typical memory chart for an application. The application that generated this chart is a slide show application that loaded a series of images one after the other.

Chapter 5: Introducing Flex Builder for Developers 95 within an acceptable range. This application could run for hours on end, and its memory usage would remain fairly constant, even though it's continu- ously creating new Image objects.

You can compare the healthy memory chart shown in Figure 5-17 with the unhealthy one shown in Figure 5-18. This new chart reflects the same applica- tion, but references to old Image objects aren't removed from the main appli- cation, so the old Image objects are never garbage-collected.

Figure 5-18: An unhealthy memory- allocation If you notice that certain interactions with your application cause the memory-allocation chart to rise and never fall back to previous levels, you may be noticing a memory leak in your application.

Profiling CPU performance In addition to profiling the memory usage of your application, the Flex Profiler can profile the performance of your application and tell you which methods are taking the most time to execute. In terms of diagnosing a slow Flex application, memory usage and performance are the two contributing factors that can lead to a bad user experience. In earlier sections in this chap- ter, you find out how to use the Profiler to diagnose memory issues; in this section, we cover how to use the Profiler to find performance bottlenecks.

Taking a performance snapshot When the Flex Profiler is running, you can take a performance snapshot by pressing the Capture Performance Profile button (refer to Figure 5-15).

This saved performance snapshot entry is added to the profiling session, just like the saved memory snapshots. You can double-click one of the per- formance snapshot entries to load a new Performance Profile panel with the details of that snapshot (see Figure 5-19).

Figure 5-19: The Perfor- mance Profile The Performance Profile panel shows you individual functions and how much time, in milliseconds, each function took to complete. Just as cumulative and individual measures indicate memory usage, cumulative and individual mea- sures gauge the performance of a function. Cumulative measures indicate the total length of time it took for the function, including any subfunctions within that function, to execute. The self-time measurements Self Time and Average Self Time report only the length of time that was spent executing within the function itself.

If you examine the results in Figure 5-19, you can see the addNextImage method took the longest cumulative time. But the processData function took the longest self-time. The reason is that the processData function gets called within the addNextImage function. So the cumulative time for addNextImage also includes the time taken by processData.

Digging into a method To further clarify which methods take the longest to process, you can double-click a particular method to open the Method Statistics panel, shown in Figure 5-20.

Chapter 5: Introducing Flex Builder for Developers 97 Figure 5-20 shows the statistics for the custom method addImage. The top pane indicates which methods called it. In this case, you can see that the addImage method was called from the addNextImage method. You can also see all other methods within addImage that were called and how much time each one took. By viewing this breakdown, it becomes clear that the processData method is the piece that takes the most time. You can then identify exactly which pieces of code are taking the most time to process and head in the right direction when you want to optimize your code.

Refactoring Your Code Refactoring is the process of reorganizing your code while preserving the functionality of that code. The term refactoring refers to the broad concept of moving things around to achieve better structure and encapsulation: changing the names of classes, moving methods from one class to another, or breaking a large class into two or more smaller classes, for example.

For a crash course in object-oriented programming methodology, refer to Chapter 3.

Changing class names The simplest reason to refactor your code is if you want to change the name of a class. The simple act of renaming a file, however, can be far more diffi- cult than it appears. To manually change the name of a class, you rename the file, and then you have to track down all references to the old class in your code and update them with the new name. Luckily, Flex Builder has built-in support for this kind of refactoring.

The following steps guide you through refactoring a class in your Flex project: 1. In the Flex Builder, select the file in Flex Navigator view, right-click, and choose Rename, as shown in Figure 5-21.

Alternatively, you can choose File?Rename. Either approach loads the refactoring wizard to step you through the refactoring process.

When you rename a class, enter the name of the class, not the full name mxml, for example, notice that the name that appears in the refac- It's the name of the class. To rename it, you should enter a different name and still omit the file extension. In Figure 5-22, the new name is MyNewlyNamedComponent.

Figure 5-21: Accessing the Rename menu item to begin Figure 5-22: Entering a new class name in the refactoring wizard.

If you deselect the Update References check box, Flex Builder doesn't refactor your code; it only renames the file. You then have to manually look through your code and change any references to the class.

If you select the Rename Textual Matches in Strings check box, Flex Builder performs a deeper text search in your source code and replaces any string references to the old filename. Be careful with this option, and make sure that you follow the next step and click the Preview button to double-check that Flex Builder is doing what you want.

Preview view shows you each change in your source code that Flex Builder will perform. This way, you can double-check and verify that all the changes are appropriate. In Figure 5-23, you can see that this refac- toring results in an updated reference to the CustomComponent class within the MyFlexProject application, as well as the moving (renaming) of the CustomComponent MXML file.

Your code is now refactored and should still compile and run with the new class name.

Chapter 5: Introducing Flex Builder for Developers 99 Figure 5-23: Previewing the refactoring changes.

You can use the Rename refactoring method on both MXML and ActionScript class files. The preceding steps show you how to rename a custom MXML class, but the same process works for ActionScript classes as well.

Changing method and variable names In addition to changing the names of classes, you can use the refactoring capabilities of Flex Builder to rename individual methods and variables within your classes. This process is similar to how you rename a class, although to invoke method or variable renaming, you need to select the method or variable name within your class, right-click, and choose the Rename menu item. Figure 5-24 shows how to invoke the refactoring wizard on the method named showStatusAlert in a custom class.

The same method of right-clicking and choosing the Rename menu item is used when renaming variables. After you invoke the refactoring wizard, either for method renaming or variable renaming, the steps are the same as they are for renaming a class.

Living with limitations The refactoring support in Flex Builder 3 is limited to simple class and method renaming. However, when you refactor applications, you often change the package structure of classes as well, which means moving source files from one directory to another to better organize the class hierarchy. Flex Builder 3 doesn't support this kind of package-level refactoring. If you need to refactor your code more aggressively and move classes between packages, you have to do most of it manually.

As we discuss in Chapter 4, Flex Builder is based on the Eclipse IDE, a power- ful editor that can be used to edit much more than Flex and ActionScript code. If you're familiar with using Eclipse for Java development, you will likely notice that the refactoring options in Flex Builder fall very short of the refactoring support for Java. You have to learn to live with this limitation until Adobe beefs up the refactoring capabilities in future versions of Flex Builder.

Chapter 6 Visually Designing Applications in Flex Builder In This Chapter Visually assembling Flex applications in Design mode Selecting, positioning, and sizing controls Inserting components with Components view Working with states in States view Setting properties on controls with the Flex Builder properties inspector Styling Flex elements using the CSS Design mode feature F lex Builder enables you to develop applications in either Source mode or Design mode. In this chapter, we focus on Design mode, which enables you to visually assemble Flex applications and components. In the other mode, Source mode, you can write code that can be visually rendered when switched into Design mode; see Chapter 5 for details about this mode.

This chapter gives you the lowdown on how to work in Design mode to create and visually customize Flex components; set properties, styles, and events on components in the design area; navigate the design area with fine control; create states for your Flex applications; and style components in detail.

Getting to Know Flex Builder Design Mode Flex Builder has two modes for wiring up Flex components and applications: Source mode refers to the robust ActionScript editor, debugger, pro- filer, and other code-related features, such as code refactoring (where name changes in the code propagate throughout your project), that Flex Builder has to offer.

Design mode is the Flex Builder mode that allows developers and designers to visually assemble applications and components. Design mode is the visual representation of the code that's created in Source mode; similarly, Source mode is updated with code when you create Flex content in Design mode.

To switch between Source mode and Design mode, you use the Source and Design buttons, which are located in the upper-left corner of the main pane of the Flex Builder window, as shown in Figure 6-1.

Design mode Source mode Figure 6-1: Flex Builder in Source mode with the Source button selected.

To see Design mode, shown in Figure 6-2, just click the Design button. This list describes the various areas identified in the figure: Design stage: Featured in the default layout of Design mode (it's the area in the center), where components and containers appear and are modified.

Design toolbar: Located above the design stage; used to pan and zoom in the design stage and to adjust the design area dimensions.

Flex Navigator view: Lets you navigate your projects and their source files.

Chapter 6: Visually Designing Applications in Flex Builder 103

Components view: Allows Flex components and custom components to be dragged to the stage.

Outline view: Provides a visual outline of the hierarchy and contents of your Flex application in its current state.

States view: Lets you partition your application into new states as well as edit already configured states. Using this view to create and edit states is often the preferred way to author states (preferred over hand- coding states in Source mode).

Properties inspector: Contains a series of panels that allow the setting of properties and styles of the selected Flex item or set of items on the stage.

The rest of this chapter covers each of these elements of Design mode in more detail.

Flex Navigator view Outline View Figure 6-2: The default view of Flex Builder Design mode.

Design stage Design toolbar States view

Navigating Through the Design Area The size of the Flex Builder design area can be customized for your conve- nience. Some developers like to work in a fixed design area, whereas others don't mind scrolling around the design area to produce a more detailed view of the design stage.

You control the design area size and navigation capabilities by using the Design toolbar (shown in Figure 6-3). By default, the design editor size is set to Fit to Window, which means that it doesn't display scrollbars and instead adjusts its layout, if possible, to fit the design window size. This size is the most convenient one to work with. You can change the design editor size by using the design area drop-down list. Other options include preset fixed sizes, such as 1024 x 768 or 800 x 600, or you can enter your own sizing dimensions by choosing the Custom Size option.

Pan mode Show Surrounding Containers Zoom Figure 6-3: You can control the dimen- sions of the design stage.

Magnification If the size of your layout is larger than the design editor window, Flex creates scrollbars to preserve the layout.

In addition to adjusting the dimensions of the design area, Flex Builder offers a way to navigate the design area with great control, as discussed in the fol- lowing sections.

Using Pan & Zoom Flex Builder 3 added the useful and cool feature Pan & Zoom. You can use it to Zoom into the design area: Observe the fine-grain visual details of com- ponents on the design stage.

Chapter 6: Visually Designing Applications in Flex Builder 105

Panning To enter Pan mode, you click the Pan Mode button, in the upper-right bank of navigation buttons (refer to Figure 6-3). To enter Pan mode from the key- board, press the H key after you have clicked on the design stage. In Pan mode, the cursor turns into a hand icon. To navigate in Pan mode, hold down the mouse button while moving in the application. You see that this type of navigation is much easier and faster than using the design area scrollbars, especially to navigate to hard-to-reach parts of the application when you zoom into the design area.

Zooming Whenever you zoom in or out, the magnification percentage is displayed in the Magnification drop-down list. The list, which is the rightmost input field on the Design toolbar, is located in the upper-right area of the design stage. You can zoom in and out of the design area in a few different ways: Open the magnification drop-down list and select a specific zoom percentage.

Right-click in the design area to open the design context menu, which has options to zoom in or out of the design stage or to set the magnifica- tion of the stage to preset values.

To enter Zoom mode without using the menu options, press the Z key or click the Zoom button after you have clicked on the design stage, on the Design toolbar (refer to Figure 6-3).

When you enter Zoom mode, the cursor turns into a magnifying glass next to a + or ? sign, depending on whether you're zooming in or out. To zoom in, press Ctrl+= (or Ô+= on the Mac); to zoom out, press Ctrl+? (or Ô+? on the Mac).

After you start using pan and zoom when working on the design stage, you can achieve greater fidelity when skinning and styling components. The reason is that you can zoom in to view more detail regarding the visual appearance of components on the design stage.

Showing surrounding containers The Flex Builder design area has a neat feature that allows you to visual- ize the nesting and hierarchy of containers in your Flex applications. This feature can be useful when determining the layering of containers in your Flex application or when you want to quickly select a particular container instance from many nested containers.

To enable this feature and show nested containers, click the Show Surrounding Containers button on the Design toolbar (refer to Figure 6-3). When you click this button, the top-level container in the design stage is overlaid with a semitransparent film to differentiate it from other contain- ers, as shown in Figure 6-4. As you click other containers in the application, they too are overlaid with a transparent film; additionally, each container is affixed with a label specifying its type and its id value if it's set. To exit this Nested Container mode, simply click the Show Surrounding Containers button again. To trigger Show Surrounding Containers by using a keyboard shortcut, simply press the F4 key on the keyboard after having clicked on the design stage.

Figure 6-4: Use the Show Surrounding Containers button to show the nesting of multiple containers.

Figure 6-4 shows a Canvas container with a Panel child container that has an HBox child container. In Show Surrounding Containers mode, notice how a transparent overlay is drawn over each container and each container is labeled with its type and id value.

Chapter 6: Visually Designing Applications in Flex Builder 107

Figure 6-5: Select multiple components on the design stage by draw- ing a box around them with the mouse.

Select a component: On the design stage, click the component's visual representation on the design stage or select the component in Outline view. You can learn more about the Flex Builder Outline view in the ?Viewing the Contents of Your Application in Outline View? section.

Select multiple components: You can select multiple components on the design stage in several ways: · Ctrl+click (or Ô+click on the Mac) on each component you want to select.

· Click into the design stage with the mouse and draw a box that overlaps all components you want to select. Notice that an overlay is drawn that visualizes which components are selected by this action, as shown in Figure 6-5.

· Ctrl+click (or Ô+click on the Mac) multiple components in the Flex Builder Outline view.

Selecting multiple components is useful when you want to reposi- tion multiple controls simultaneously, delete a set of controls, or set common properties on multiple controls.

Select all components on the design stage: Open the design menu by right-clicking the design stage (or Ô+clicking it on the Mac) and choos- ing the Select All menu option. Similarly, you can type Ctrl+A (or Ô+A on the Mac) to select all components on the design stage by using a key- board shortcut.

Deselect a single component or multiple components: Click in the back- ground of any container in the design stage, click an unselected com- ponent on the design stage, or click in the gray margin surrounding the root component.

To delete a component or many components on the design stage, you simply select the components you want deleted and press the Delete key on the key- board. Similarly, after having selected the components you want to delete, you can right-click (Ctrl+click on the Mac) the design stage to open the Design menu and then select Delete from the menu options, as shown in Figure 6-6.

Figure 6-6: Right-click the design stage to open the Design Controlling the Layout and Size of Controls in the Design Area Flex Builder offers a plethora of features that allow you to control the layout and size of controls on the design stage. Knowing how to use these features can greatly improve your efficiency and ability to construct complex, pixel- perfect layouts.

Positioning controls You can control the position of components on the design stage in quite a few ways. Be sure to note that the behavior of the parent container affects how child components are positioned on the design stage: In absolute positioning containers, such as Canvas, or containers that have the layout property that can be set to absolute (such as Panel, TitleWindow, or Application), child controls can be positioned at any x and y value.

In relative layout containers, such as HBox and VBox, child controls can be positioned according to the layout rules of their parents.

Chapter 6: Visually Designing Applications in Flex Builder 109

You can drag and drop all controls on the design stage to reposition them on the design stage. Remember that you can also set position and size-related properties in the properties inspector and the controls on the design stage (as well as the code generated in Source mode) are then visually updated automatically. Often, when the visual designer gives you fixed positions for controls, it's easier to enter these values into the x and y input fields in the properties inspector to achieve pixel-perfect accuracy. Flex Builder's proper- ties inspector is discussed in further detail in the ?Configuring Controls with the Flex Builder Properties Inspector? section, later in this chapter.

To reposition a control that's already on the design stage, simply select the control and drag it. The cursor changes into a four-arrow cursor. As you drag the controls, you see only the outline of the controls being dragged, which results in a clearer view.

After you have repositioned controls that reside in an absolute positioning container, the properties inspector is updated to report the new x and y values for the controls.

When you reposition controls that reside in relative layout managers, such as HBox or VBox, you notice that as you drag around a control or a set of con- trols, you see a blue line indicating the new position of the control relative to the other child controls living in the container (see Figure 6-7). This visual cue indicates where the newly dropped control will be positioned.

Blue line Figure 6-7: A blue line is used as a visual cue to show where the new compo- nent will be inserted.

You can also nudge a set of controls with the arrow keys. It's an easy way to move a bank of components by just a few pixels in any direction. Simply select a set of components and use the arrow keys to move controls en masse to the right, left, top, or bottom.

Snapping controls relative to each other As you drag controls around, or drag out new controls from Components view to the design stage in a container that has absolute positioning, blue lines appear at certain positions. Using this Flex Builder snapping feature, you can position controls relative to others in order to line them up vertically or horizontally.

The Flex Builder snapping feature is available only when you're repositioning controls that are in absolute positioning containers, such as Canvas, or Panel, TitleWindow, or Application, with the layout property set to absolute.

As you reposition controls, Flex Builder hints where snapping will occur. When the edges of repositioned controls line up with the edges of other sibling controls, a blue line appears to show the snapping position. This behavior is helpful for lining up components, especially text components, along a common baseline. Using snapping ensures that the components are aligned so that their text is in a single line. Figure 6-8 shows how three components ? a Button, TextInput, and CheckBox ? have been aligned according to their text by using snapping. Notice that when you drag a new component from Components view, the blue snapping lines indicate where to drop the control so that its text is aligned with the already aligned Button, TextInput, and CheckBox.

Snapping is turned on by default, but it can be turned off to clear the design stage of visual hints. To turn off Flex Builder's snapping behavior, choose Design?Enable Snapping. To enable or disable snapping as a global prefer- ence in Flex Builder, choose Windows?Preferences to open the preferences dialog box, navigate to Flex?Editors?Design Mode, and select or deselect the Enable Snapping check box.

Aligning controls Flex Builder has built-in functionality to help manage the alignment of child controls in layout containers that support absolute positioning (Canvas, Application, Panel, and TitleWindow). One of the more robust ways to con- trol alignment is to use a constraint-based layout by using the Constraints control in the properties inspector. To find out how to use this control, check out the section ?Setting constraints visually with the Constraints Control,? later in this chapter.

Chapter 6: Visually Designing Applications in Flex Builder 111

Blue snapping line Figure 6-8: The snapping feature shows where to drop the control for good alignment.

Additionally, Flex Builder allows the alignment of a set of controls alongside their left edges, right edges, centers, top edges, lower edges, or baselines by using Design menu options. First, select a set of controls that you want to align relative to each other. Next, open the top-level Design menu. Notice the options: Align Left, Align Vertical Centers, Align Right, Align Top, Align Horizontal Centers, Align Bottom, and Align Baselines. When you choose these Alignment menu options, the set of selected controls align accordingly.

Table 6-1 Flex Builder Alignment Options Option Description Align Left Aligns the left edges of all selected controls with the left Align Vertical Aligns the vertical centers of all selected controls with the Centers vertical centers of the first component that was selected. Align Right Aligns the right edges of all selected controls with the right Align Top Aligns the top edges of all selected controls with the top Align Horizontal Aligns the horizontal centers of all selected controls with the Centers horizontal center of the first component that was selected.

Table 6-1 (continued) Option Description Align Bottom Aligns the bottom edges of all selected controls with the Align Top Aligns the top edges of all selected controls with the upper Align Baselines Aligns the text of all selected controls with the text of the first component that was selected. If any of the selected controls doesn't have text, the bottom edge of the control is considered its text baseline.

Figures 6-9 and 6-10 demonstrate how alignment works. Figure 6-9 shows components that we dragged from the Components view and placed haphaz- ardly next to each other. We chose the Align Right option to align the right edges of all the controls with the top Button, as shown in Figure 6-10. We selected the top Button first to force the rest of the components to align their right edges with its right edge.

Figure 6-9: A set of controls that aren't aligned respective to each other.

Sizing and resizing controls Controls can be resized directly on the design stage or through the proper- ties inspector, and this resizing is reflected visually as well as in the gener- ated code in Source mode.

Chapter 6: Visually Designing Applications in Flex Builder 113

Figure 6-10: A set of controls that have their right edges aligned with each other.

To resize a control directly on the design stage, follow these steps: 1. Select the control you want to resize.

To help you in deciphering the new size of the control after the resize action has completed, a ToolTip next to the resizing component displays the new width and height values.

You can also resize controls by modifying the width and height values in the properties inspector. You can enter pixel or percentage sizes in the width and height input fields.

Inserting Components with the Components View Flex Builder Components view, shown in Figure 6-11, is often docked to the left of the stage area in Design mode. If it's not there, you can open it by choosing Window?Components. You can drag Flex components and contain- ers from the Components view and drop them on the stage.

Figure 6-11: Components view in Flex Builder Design Flex Builder Components view is organized into four folders of components, as described in the following list: Custom: The Custom folder holds references to any custom components written in either MXML or ActionScript files in the current project or the source path of the current project. When you drag a custom component to the stage, Flex adds the corresponding code to Source mode to indi- cate that the component has been added to the application.

Controls: The Controls folder contains a list of all Flex user interface controls, such as Button and TextInput. When you drag controls from the Controls folder to the stage, the controls assume a default size and appearance. For example, dragging a Button from the Controls folder creates a button large enough to display the label `Button'.

Containers: The Containers folder contains a list of all Flex layout containers, such as HBox and Panel. After you drag any of the relative layout containers to the design stage, a sizing dialog box appears (simi- lar to Figure 6-12). In this dialog box, you can specify how the container should be sized.

Here are your sizing options, based on the type of container: · For the Form, HBox, HDividedBox, VBox, and VDividedBox contain- ers: The default sizing option is to give the container 100 percent of its parent's width and a default height. To change this behavior, enter values into the dialog box to specify either a pixel or percent- age size value for the container's width and height.

· When dragging a Tile container: The default sizing option is to size the Tile container to its contents. You specify a pixel or percentage size value for the container's width and height.

· When dragging a Grid container: The dialog box lets you determine how many rows and columns the Grid container should contain.

Chapter 6: Visually Designing Applications in Flex Builder 115

· For all other options in the Containers folder (such as Panel and Canvas): Flex Builder chooses a default pixel size that can be resized however you want.

Navigators: The Navigators folder contains a list of all navigator controls, such as Accordion and TabNavigator. When you drag a Navigator to the design stage, it's decorated with a little toolbar displaying + and ? buttons. You use these buttons to add and remove child views. (For more on Flex Navigators, see Chapter 10.) When adding new child views, you can use the dialog box that opens after you click the + button to specify the child view container and its label. Similarly, the ? button can be used to delete the selected child view.

Figure 6-12: The siz- ing dialog box for the HBox Viewing the Contents of Your Application in Outline View When you use Flex Builder Outline view, shown in Figure 6-13, you can inspect the structure of your MXML application. Outline view is often the sib- ling pane to Components view and is usually docked to the left of the design stage. If the Outline View pane isn't open, you can manually open it by choos- ing Windows?Outline.

Outline view lists all Flex components created in MXML that exist in your Flex application. It gives you a neat way to view the hierarchy and organization of your Flex application. You can select single components or multiple com- ponents by Ctrl+clicking in Windows or Ô+clicking on the Mac; the controls appear as selected in the design stage. This selection allows you to Adjust the position of a single component or a set of components en masse.

Figure 6-13: Outline view in Flex Builder Design Working with States in States View Flex uses the states concept, which you can use to create different views of your application. The Flex Builder States view, shown in Figure 6-14, is a handy interface for creating, deleting, and editing Flex states. (To find out more about Flex states, refer to Chapter 17.)

New State button Edit State button Delete State button Figure 6-14: You can create a new state in States view.

Chapter 6: Visually Designing Applications in Flex Builder 117

The base state of your Flex application consists of all Flex elements defined in the Flex application up to the point where the new state is created.

2. In the States dialog box, name the state and choose which existing state the new state should be based on. Then click OK.

As you create new states, the hierarchy is displayed visually in the States view. For example, if State 1 is based on State 2 and State 2 is based on State 3, States view lists the states in such a way that State 1 is the parent of State 2, which is the parent of State 3.

Suppose that your application needs a login view that people use to log in with a username and password. The base state of the login view is simply a Panel container with a Login button. When users click the Login button, a dif- ferent view appears, where they can enter their usernames and passwords. In this case, the base state of the login view is simply the Panel container with the Login button, as shown in Figure 6-15.

Figure 6-15: The base state of the login panel ? you build subsequent states based on this state.

Using the New State button, you create a second state: loginInputs. In this view of the login panel, application users can enter their usernames and passwords. After you create this new state, which is based on the base state, notice that the States view shows the hierarchy of states ? namely, that loginInputs is based on the base state, as shown in Figure 6-16.

New state Figure 6-16: Flex displays a second state for the login panel component, loginInputs, where appli- cation users can enter their information.

The following list gives you the lowdown on how to delete or edit a state: To delete a state: Select the state entry in States view and use the trash- can icon (Delete State button) on the States toolbar to delete the state. The state is then removed from States view, and the corresponding code is removed from the application.

To edit a state: Click the pencil icon (Edit State Properties Button) on the States toolbar. In the Edit dialog box that appears, edit the name of the state and the existing state it's derived from. Remember that what- ever is on the design state and associated with a defined state encom- passes the view of that state in the application.

Configuring Controls with the Flex Builder Properties Inspector Using the Flex Builder properties inspector, you can visually set properties, styles, and event handlers for all components defined in your application. The properties inspector is traditionally located to the right of the stage area in Flex Builder Design mode, in the Flex Properties pane, as shown in Figure 6-17. If you don't see the Flex Builder properties inspector, you can open it by choosing Window?Flex Properties.

Chapter 6: Visually Designing Applications in Flex Builder 119

Category view Alphabetical view Figure 6-17: The properties inspector shows all properties, styles, and events that you can set for the con- trol that's selected on the design stage.

Choosing a properties inspector view The properties inspector has three different views for setting properties, styles, and events on controls selected in the stage area: The properties inspector's Standard view splits the pane into proper- ties, styles, and events that are commonly set on that control (in the Common pane), those that are style related (set in the Style pane), or those that are layout related (set in the Layout pane).

Standard view is the easiest view of the properties inspector to use, so we recommend it.

Category: In this view, elements that can be set on the selected compo- nent in the design stage are grouped in common categories along with their set values. That is, all events that are valid on the selected compo- nent are located in the Events category; similarly, style-related proper- ties are in the Styles category.

You can switch to Category view by clicking the Category View icon at the top of the properties inspector panel (refer to Figure 6-17).

Alphabetical: This view simply lists all properties, events, and styles that can be set on the selected component on the design stage in alpha- betical order along with their values. It's the last button in the upper- right corner of the properties inspector panel (refer to Figure 6-17).

Using the properties inspector When a control is selected on the design stage, the properties inspector is updated to display input items that correspond to the properties, styles, and events that you can set for that component. For example, when you select a DataGrid control, the Common panel in Standard view of the properties inspector shows the properties and events commonly settable for a DataGrid control (see Figure 6-18).

Figure 6-18: When you select a DataGrid control, the properties inspector shows the properties, events, and styles that you can set on that control.

When multiple controls are selected on the design stage, the properties inspector is updated to display only the properties, events, and styles that are common among all selected components.

As you enter values for properties in the input fields, the selected component on stage is updated in real time to reflect the changes. For example, when you enter a value in the Column Width field and then press Enter, the DataGrid control on the stage is updated to display the new column widths.

Chapter 6: Visually Designing Applications in Flex Builder 121

Setting constraints visually with the Constraints Control When you select a control or multiple controls that reside in an absolute- positioning container, the Layout pane in the properties inspector displays the special control named Constraints, as shown in Figure 6-19. You can use this control to create new layout constraints or edit existing layout con- straints on the controls selected in the design stage. (To find out more about constraint-based layout and how you can use it to build reflowing layouts, check out Chapter 10.)

Figure 6-19: Use the Constraints control to visually set layout constraints on child controls rel- ative to their parenting container.

The check boxes in the Constraint control correspond to the setting of the left, right, top, bottom, horizontalCenter, and verticalCenter layout constraints. When you select one of these check boxes, Flex calculates a constraint value that anchors the selected control on the stage to the edge of its parent.

constraint check box is selected ? appears in the text box in the constraint control. You can also enter values into the text box, and Flex adjusts the posi- tion of the selected control to match the new constraint value. When you switch to Source mode, you see that the selected control, which had layout constraints set on it by way of the Constraint control, has the appropriate code set in the component tag corresponding to the newly created constraints.

For example, in Figure 6-20, the selected control has a left constraint set to 50 pixels and a verticalCenter constraint set to 100 pixels. In Source mode, the component tag looks like this:

One neat thing that Flex Builder Design mode does is track the changes you make to your application, in either Design mode or Source mode. Whenever a change is made to the state of your application, such as adding a new com- ponent from Components view or setting a property on a component from the properties inspector, this change is tracked. You can then easily undo the action by either pressing Ctrl+Z (or Ô+Z on the Mac) on the keyboard or choosing Edit?Undo. To redo the action, simply press Ctrl+Y (or Ô+Y on the Mac) on the keyboard or choose the Edit?Redo menu option in the top-level Flex Builder menu.

Chapter 6: Visually Designing Applications in Flex Builder 123

Working with Style Sheets in CSS Design Mode New in Flex Builder 3 is the powerful feature: CSS Design mode. You can use it to visually display and edit the contents of a CSS style sheet whose style blocks are used to style your Flex components. To use CSS Design mode, you need to open a CSS style sheet in Flex Builder. To switch to CSS Design mode, simply click the Design button in Source mode in the upper-left corner of the code editor.

CSS Design mode shows the different states that a component can enter and allows you to visually customize what the control looks like in those states. When you make edits in CSS Design mode, Flex updates the resulting style blocks in the CSS style sheet with the corresponding code that results in the visual appearance you chose. (To find out more about using CSS style sheets, class selectors, and type selectors in your Flex applications, see Chapter 18.) To create new style blocks in your CSS style sheet, follow these steps: 1. Click the New Style button in the toolbar at the top of CSS Design mode, as shown in Figure 6-21.

Figure 6-21: New Style Click the Delete Style New Style button to start creat- ing a new style.

2. Choose one of these selector types: · All Components (global): Create a style block that (if possible) affects all components in the application. This is an easy way to create a font style or size that's percolated down to every compo- nent in the Flex application.

· All components with style name: Create a new type selector of a par- ticular name.

· Specific component: Create a new class selector for all components of a specific type.

· Specific component with style name: Create a style block for all particular types of components that you chose to apply the style name to.

You can create a new style selector, either a class selector that can be applied to all Flex components of a particular type (such as all Buttons) or a type selector that can be a custom style block you define and apply to components of your choice.

Figure 6-22: Choose which type of style block you want to cre- ate in your CSS style sheet.

3. Depending on which selector type you chose in Step 2, choose which component you want to use to visualize the style entries. (If you selected All Components in Step 2, you can skip this step.) For example, if you want to create a class selector or a type selector for Button-related controls, ensure that the Button control is selected as the Component option.

After you click OK, the component that the style block is based on shows up on the design stage in all the different states it can assume. For example, when you're creating a type selector for the Flex Button control, different buttons representing the different various states the Button can enter (such as up, down, over, and selected) are displayed on the design stage. You can use the properties inspector (shown in Figure 6-23) to customize and edit all styles that dictate how the Button looks when it enters that state.

As you create new style blocks, the Style drop-down list on the top toolbar becomes populated with the names of the style blocks. You can use this drop-down list to determine which style block is visualized on the design stage. Also, if you open an existing CSS style sheet that already has style blocks created, the style drop-down list is populated with the style names, and you can select and further modify them with the properties inspector.

Chapter 6: Visually Designing Applications in Flex Builder 125

Figure 6-23: You can use CSS Design mode to change the rollover color of a Button control from blue to red in its differ- ent states.

To delete a style block from your CSS style sheet, chose the style entry from the Style drop-down list in the top toolbar and click the Delete Style button (refer to Figure 6-21).

As you dive further into the topic of styling your Flex components, you find that CSS Design mode is a powerful tool to visualize the specific look of com- ponents and modify them in detail.

P repare to dive headfirst into the Flex framework and power all the way through. This part covers every- thing from a simple Button control to the data-driven There's a reason that Part III is the longest part in this book: It contains the meat of the Flex framework. At some point in your Flex career, you will use every component covered in Chapters 7 through 11.

We begin in Chapter 7 with some of the simplest compo- nents, such as Label and TextInput, and then we move to Chapter 8 to cover controls such as DataGrid and Tree, which are driven by underlying data models. We then We finish this part by describing the charting compo- nents, which are sure to impress the executives in your organization.

Chapter 7 Simple User Interface Controls In This Chapter Creating clickable user interface controls, such as Button and ComboBox Working with text controls, such as Label and TextInput Using media display controls, such as Image and VideoDisplay Building a media controller, such as a video player T he Flex framework offers a wide set of user interface controls for you to use while building your Flex application. User interface controls are the visual elements that appear in a Flex application. A large number of Flex user interface controls are available for you to use, and you can customize all of them based on the functionality or visual appearance you want.

In this chapter, we discuss how to create, display, and make common cus- tomizations to clickable controls, text display controls, and media display controls. These controls are some of the most essential building blocks in the Flex framework, and you use them repeatedly. The following list shows the user interface controls discussed in this chapter:

Taking a Look at Simple Clickable Controls Flex comes replete with a rich set of clickable user interface controls. These controls range from a simple Button and CheckBox to controls that encapsu- late advanced functionality, such as ComboBox. The ComboBox control pops open a drop-down list prepopulated with options. You can easily define these clickable user interface controls in your Flex application and subsequently build a rich user interface. You can customize their functionality and visual appearance by setting properties and styles. In the following sections, we describe how to create and customize all the clickable user interface controls available in Flex.

The following sections discuss the various user interface controls that you use to build Flex applications. But before jumping into reading about these controls, you should understand the inheritance hierarchy of Flex controls. The Flex framework was written with extensibility in mind, which means that any Flex control can be extended to add new functionality or to create a whole new control. Extension is possible because Flex controls already inherit from each other. If you look at the Flex framework source code available in your FlexBuilder installation directory, you see that the mx.controls.CheckBox class extends the mx.controls.Button class. Because of this relationship, a CheckBox control inherits all the properties, events, methods, and styles declared in the Button class. This concept of inheritance is very powerful for Flex developers to understand. For a more in-depth review of the Flex inheri- tance hierarchy, check out Chapter 3.

For the most part, visual Flex components inherit from a single, basic class: mx.core.UIComponent. A UIComponent control represents the most basic Flex control. It provides properties, styles, and events that can be set to cus- tomize the control's visual appearance or functionality. All visual Flex con- trols can eventually trace their inheritance hierarchy back to UIComponent, thus making UIComponent the ancestor of all Flex controls! This inheritance hierarchy is shown in Figure 7-1.

Creating button-based controls The Flex framework offers a variety of button-based controls. Button-based means that all controls in this section can trace their inheritance hierar- chy back to the mx.controls.Button class. A user can click a button- based control to perform a new action or make a selection. These types of button-based controls include the Button, CheckBox, RadioButton, RadioButtonGroup, LinkButton, PopUpButton, and PopUpMenuButton con- trols. These controls are described in more detail in the following sections.

Chapter 7: Simple User Interface Controls 131 mx.core.UIComponent

Figure 7-1: Inheritance hierarchy mx.controls.Button mx.controls.Label mx.controls.TextInput

for a subset of Flex mx.controls.Text mx.controls.CheckBox mx.controls.RadioButton

Button The Button control is what you would expect: a simple, rectangular button that the user can click. You create a Button control in a Flex application by using the MXML tag. You can customize a Button control to display a label, an icon, or both a label and an icon together. As with all other Flex controls, you can customize a Button control's visual appearance to its fine-grain detail.

You can also add event listeners to the Button control to detect when the button has been clicked and then perform an action in response to that click. The most common event that's listened to on a Button control is click. This event is fired by the button every time the user presses and releases a Button with the mouse or keyboard. To refresh your knowledge of events and event listeners, refer to Chapter 3.

You can set properties and styles for the Button control as described in the following list: Add a text label: You can set the label property on the Button con- trol to specify which text should be displayed on the button. Then, to control the placement of the label, use the textAlign style. Its default value is center: The label appears in the center of the button. You can customize the button to display the label as left-aligned or right-aligned by setting the textAlign style to left or right.

Display an icon: In addition to being able to add a label, you can have the Button control display an icon. To specify an icon, you set the icon style. The icon style expects an image that's embedded in the Flex application at compile time. (For more on the types of images you can embed in a Flex application, and the correct syntax to do so, see Chapter 18.) Position the label and icon: You can control the placement of the but- By default, the label is placed to the right of the icon. However, you can set labelPlacement to left, right, top, or bottom to set the ori- entation of the label with respect to the icon. Figure 7-2 shows buttons with different labelPlacement values in use.

Figure 7-2: Label- placement The example shown in the following code snippet shows a Trash button that you might use in a Flex application (see Figure 7-3).

Figure 7-3: A Button control with an icon and An icon is displayed above the label, and this orientation is configured by using the properties and styles just described. This example includes a click event listener, which listens for the click event to be dispatched by the Button and then invokes the trash method to handle the response.

The toggle property controls whether a button supports toggling, which means that when someone clicks the button, it stays selected until someone clicks it again. If the toggle property is set to false, the button doesn't stay pressed after the user finishes clicking it. If you choose to use the toggle property, the selected property may also come in handy. The selected property takes effect only when the toggle property is set to true. The selected property, when set to true, visually renders the button as selected.

This property makes more sense with some of the other Button-based con- trols, such as CheckBox and RadioButton. When selected is set to true in these controls, CheckBox appears with a check mark displayed in the box, and RadioButton appears with the radio icon filled in. Figure 7-4 shows what the Button, RadioButton, and CheckBox controls look like when the toggle property and selected properties are set to true.

Chapter 7: Simple User Interface Controls 133 Figure 7-4: Selected and toggled controls.

CheckBox A CheckBox control displays a descriptive label and a box that can show a check mark to indicate selection. The CheckBox control extends from the Button control and thus inherits all properties, styles, methods, and events declared on the Button control. You can create a CheckBox control in a Flex application by using the MXML tag. Similar to how you work with a Button control, you often add a click event listener to detect when a user clicks the CheckBox control. The clicking of the check box causes the selection to take place and the check mark to be drawn in the box. The following example shows a CheckBox control that, when clicked, visu- ally indicates that the user will receive a copy of his order in e-mail form (see Figure 7-5).

Figure 7-5: A selected CheckBox We added a click event handler so that when the CheckBox control is selected, the emailReceipt method is called. Notice that the CheckBox MXML tag has its selected property set to true, which means that the check box is initially displayed as selected, with the check mark drawn in the box:

RadioButton The RadioButton control is another extension of the Button control, so it inherits all properties, styles, methods, and events defined by the Button control. You can create a RadioButton control in a Flex application by using the MXML tag. A RadioButton control displays a label and a circle that are filled in with a radio icon when selected. You can use event listeners to determine when the RadioButton control has been selected. Like all button-based controls, the click event is the most common event that is listened for. The click event is dispatched when the user clicks a radio button to select it.

Normally, you allow only one RadioButton control in a set of RadioButton controls to be selected at a time. Application users can select a single radio button from a set of mutually exclusive radio buttons. Selecting another RadioButton control deselects the previously selected radio button. You can make your radio buttons act like this by using the same groupName property for all buttons you want to group.

The following example shows two RadioButton controls that let users report their gender (see Figure 7-6). Because we used the same groupName prop- erty for both controls, only one radio button can be selected at a time:

Figure 7-6: Two RadioButton RadioButtonGroup If you want to take the concept of grouped RadioButton controls a step fur- ther than just RadioButton, you can create a RadioButtonGroup. It gives you more control over how your set of RadioButton controls behaves. You can define a RadioButtonGroup in MXML by using the tag. However, the RadioButtonGroup control isn't a visual control, so the tag doesn't render anything in your Flex applica- tion. This makes the control faceless in Flex. The special RadioButtonGroup control indicates that a set of RadioButton controls should be treated as a group. You create a RadioButtonGroup when you want the same action to occur when any of the RadioButton controls within the group is selected. In this manner, RadioButtonGroup ?governs? the selection of each individual RadioButton control defined within the group.

When a radio button that's part of a RadioButtonGroup is selected by using the mouse or keyboard, the RadioButtonGroup receives a change event. By adding an event listener for the change event, you can ensure that all radio button selections are proxied through to the action specified by the change event handler.

Chapter 7: Simple User Interface Controls 135 RadioButtonGroup control rather than have to define click event handlers on each individual RadioButton control:

LinkButton The simple button-based LinkButton control is used to show links in a Flex application. As the user hovers over the LinkButton, its contents are high- lighted. You can create a LinkButton control in your Flex application by using the MXML tag. As with all other button-based controls, you can detect when a user clicks the LinkButton by adding an event listener for the click event.

You can control the visual appearance of the LinkButton as the application user is interacting with it by setting a couple of styles in the LinkButton tag: rollOverColor: Controls the color of the entire LinkButton as the user hovers the mouse over it.

textRollOverColor: Controls the color of just the label as the user hovers the mouse over it.

The following example shows a LinkButton control that, when clicked, navi- gates the user's browser to the Adobe Systems Incorporated home page:

As the user hovers over the LinkButton, shown in Figure 7-7, the background of the control becomes red and the text is white. You achieve this effect by setting the textRollOverColor and rollOverColor styles.

The navigateToURL method is useful for launching links to other Web sites from within your Flex application. However, you cannot simply pass a URL string to navigateToURL. Instead, you must pass a URLRequest object that specifies the URL to navigate to. The previous example shows you how to do this.

You often use LinkButton controls in conjunction with a LinkBar control to provide a set of clickable links that can be used to navigate within a Flex application. For more information on how to create a LinkBar control and to find out more about navigation controls, see Chapter 9.

PopUpButton You can use the PopUpButton control to pop up any Flex user interface con- trol when a user clicks the PopUpButton control. A PopUpButton looks simi- lar to a Button control, except that a second button with a downward arrow is affixed to the side of the Button control. When the user clicks this arrow button, a new Flex component pops up. You can create a PopUpButton con- trol in your Flex application by using the MXML tag.

You set the popUp property to specify which Flex control is used as the pop-up when a user clicks the arrow button. The popUp property expects an object that is of type mx.core.IUIComponent. mx.core.IUIComponent is the interface that all Flex controls implement, which means that you can set the popUp property to any visual control available in the Flex framework library.

Because all visual Flex controls in the Flex framework implement the mx.core.IUIComponent interface, any Flex method that expects an object of type mx.core.IUIComponent as a parameter, can accept any visual Flex control.

Every interface class in the Flex framework has an I prepended to its class name; for example, mx.core.IContainer, mx.core.IFlexDisplayObject, and mx.core.IUID. When you see the I in front of a class name, you know that the class is an interface.

The following example shows how to create a PopUpButton control that pops up a Flex button when a user clicks the arrow button (see Figure 7-8):

Chapter 7: Simple User Interface Controls 137

Notice that the popUp attribute is set as a child MXML tag of the PopUpButton MXML tag. A Button control is passed in as the value of the popUp MXML tag. That Button is the Flex control that's displayed when a user clicks the PopUpButton control's arrow.

Often, the pop-up control needs to be initialized in some way. For example, you might need to populate the pop-up control with data or add event listen- ers so that the pop-up responds to user interaction. Sometimes this means that you create the pop-up control in ActionScript and then set that newly created control as the value of the popUp property on the PopUpButton control. For the most part, you can always create the pop-up control with MXML tags, as the preceding example shows, but sometimes the pop-up con- trol must be created in ActionScript for fine-grain control of the pop-up. The following example shows how to create a PopUpButton control where the pop-up is created in ActionScript:

// Initialize the List control, and specify it as private function createPopUp ():void { var dp:Object = [{label: ?Cat?}, {label: ?Dog?}, popUpBtn.popUp = listPopUp;

} ]]> Figure 7-9 shows a PopUpButton control that displays a prepopulated List control.

First look at the createPopUp method. In this method, you first create the List control in ActionScript by using the ActionScript new operator. After you create the List control, you set its dataProvider property so that it's populated with data items. After the List control is created and populated with data, you can safely set the PopUpButton's popUp property to the newly created List control.

Figure 7-9: A prepopu- lated List Now, how is the createPopUp method invoked? Notice that the PopUpButton tag has an event listener for the creationComplete event. This event is dis- patched when any Flex control has been completely created. In the preceding example, after the creationComplete event has been dispatched, the createPopUp method is called, which safely creates the pop-up and assigns it to the PopUpButton's popUp property.

Because a PopUpButton control extends the Flex Button control, it can follow all the same customizations available to a Button control. You can therefore customize the PopUpButton control to show just a label, an icon, or a label and an icon together.

PopUpMenuButton The PopUpMenuButton control is similar to the PopUpButton control, except that the former always pops up a menu-like control. The PopUpMenuButton control creates a PopUpButton control and pops up a single-level Flex Menu control. You can create a PopUpMenuButton control in your Flex applica- tion by using the MXML tag. You can populate the pop-up menu with data directly in the PopUpMenuButton MXML tag. (For more information on creating and customizing the Flex Menu control, see Chapter 8.) The following example shows how to create a PopUpMenuButton control that displays a menu pop-up when a user clicks the arrow button. The menu pop-up allows users to select a color from three color options, as shown in Figure 7-10.

Chapter 7: Simple User Interface Controls 139 The menu pop-up is populated with data directly as a child tag of the PopUpMenuButton tag. To populate the PopUpMenuButton with data, you set the dataProvider property. In this example, the dataProvider prop- erty is set to an array of data that's declared with MXML tags. This data is displayed by the menu pop-up:

Red Blue Purple

To determine when an item on the pop-up menu has been selected, you add an itemClick event listener. The event object that's passed to the itemClick event listener has information in it that can tell you which menu item was selected. For more information on event objects and how to glean useful information from them, refer to Chapter 3.

Popping open controls with ComboBox and ColorPicker In this section, we discuss ComboBox and ColorPicker, two controls that dis- play their data in subcomponents that pop up as a result of user interaction in order to allow users to make selections.

ComboBox The simple Flex ComboBox control lets users click an arrow button to open a drop-down list from which they can make choices. You create a ComboBox control by using the MXML tag. This control is similar to the HTML tag. A TextInput control can be created with the MXML tag. When you use TextInput, you're limited to a single line of text, so this text control should be used for simple input fields that don't require multiple lines of input.

You can get and set the text that's displayed in the control by accessing the aptly named text property. To create a basic text-input control, use the fol- lowing MXML code:

Then you can access the text that the user has typed by referencing myText- Field.text. Here's a complete MXML application to demonstrate accessing the text of a TextInput control:

private function showAlertMessage():void { } ]]>

This Flex application lets an application user enter her name in the TextInput control (see Figure 7-17). When the user clicks the Submit button, an alert message pops up and displays the text the user entered in the myTextField control.

Figure 7-17: Using a TextInput control to receive user If the user is entering a password, you can set the displayAsPassword property to true, which displays asterisks to hide what the user is typing. This strategy also works on the TextArea control.

TextArea If you need the user to enter more than a single line of text, use the TextArea control rather than TextInput. This distinction is similar to the distinction between Label and Text, discussed a little earlier in this chapter. If we con- tinue our comparison to HTML controls, it should be apparent that TextArea is similar to the HTML