You are on page 1of 11

First

Steps
in
Flex
BruceEckel
President,MindViewInc.

JamesWard
FlexEvangelist,AdobeInc.


Manyofthedesignationsusedbymanufacturersandsellerstodistinguish
theirproductsareclaimedastrademarks.Wherethosedesignations
appearinthisbook,andthepublisherwasawareofatrademarkclaim,
thedesignationshavebeenprintedwithinitialcapitallettersorinall
capitals.FlexandFlasharetrademarksofAdobe,Inc.Javaisatrademark
ofSunMicrosystems,Inc.Allotherproductnamesandcompanynames
mentionedhereinarethepropertyoftheirrespectiveowners.
Theauthorandpublisherhavetakencareinthepreparationofthisbook,
butmakenoexpressedorimpliedwarrantyofanykindandassumeno
responsibilityforerrorsoromissions.Noliabilityisassumedfor
incidentalorconsequentialdamagesinconnectionwithorarisingoutof
theuseoftheinformationorprogramscontainedherein.
Thepublisheroffersexcellentdiscountsonthisbookwhenorderedin
quantityforbulkpurchasesorspecialsales.Formoreinformation,please
contactMindView,Inc.attheaddressatthebottomofthispage.
VisitusontheWeb:www.mindviewinc.com
CoverdesignandinteriordesignbyDanielWillHarris,www.Will
Harris.com
Copyright2008byMindView,Inc.
Allrightsreserved.PrintedintheUnitedStatesofAmerica.This
publicationisprotectedbycopyright,andpermissionmustbeobtained
fromthepublisherpriortoanyprohibitedreproduction,storageina
retrievalsystem,ortransmissioninanyformorbyanymeans,electronic,
mechanical,photocopying,recording,orlikewise.Forinformation
regardingpermissions,writeto:
MindView,Inc.
5343ValleVista
LaMesa,CA91941
Email:Wayne.MindView@gmail.com
ISBN9780981872506
TextprintedintheUnitedStates.
Firstprinting,August2008

Contents
Introduction ..............................................................................5
Hello,World ..............................................................................7
Events ....................................................................................... 13
ActionScript............................................................................ 17
DesktopApplications ......................................................... 29
Containers............................................................................... 33
Components ........................................................................... 39
DataandCollections........................................................... 47
ItemRenderers ..................................................................... 55
ViewStates ............................................................................. 59
Effects ....................................................................................... 63
Forms ........................................................................................ 69
Formatters .............................................................................. 73
Drag&Drop ........................................................................... 75
PopUps ..................................................................................... 77
Graphics ................................................................................... 81
StylingandSkinning........................................................... 85
Usability ................................................................................... 93
FlashPlayerAPIs ................................................................. 97
DataVisualization............................................................. 101
WebServices....................................................................... 107
RemotingandMessagingwithJava .......................... 113
ArchitecturalPatterns .................................................... 123
A:DevelopmentTools..................................................... 133
B:Deployment.................................................................... 137

Want Flex hands-on learning?


Look for the next Flex Jam on www.MindView.net

Introduction
Werenotgoingtotrytoconvinceyouto
useFlex.
Wewantedtomakeasmallbook,sowedonthave
thespace.Welljustassumethatyoualreadywantto
learnFlex,andthatyouvehadsomeexposureto
programming.
Wevefound(byrunninghandsonFlexJamssee
www.MindView.net)thatthebestwaytolearnisto
immediatelywadeinandgetyourankleswet.But
wedontwanttothrowyouintothedeependwhere
youllgetoverwhelmed.
Weretryingtogiveyoujustenoughinformation,
andjusttherightinformation,togetyoustarted.
Enoughsothatyoufeelconfidentintakingyourown
stepsonceyoufinishthebook.
Lookatthepictureonthecover.Itsascarybridge,
andalongwaydown(ThatsJamesonthebridge,in
theItalianDolomites).Onceyoutakethefirstfew
steps,though,youllhavetheconfidencetocrossthe
restofthebridge.
Asabonus,youcanfindfreescreencastsofBruce
andJamescoveringeverychapterinthisbookat
www.FirstStepsInFlex.com.
Animportantgoalforthisbookisthatitbeatool
thatcompaniescaneasilybuyinbulk,tostart
everyoneontheirfirststepstolearningFlex.Italso
makesanicegiftatconferences.Contactusat
www.MindView.netfordetails.

Hello, World
BuildyourfirstFlexapplications.
First,downloadandinstallthe60dayfreetrialof
FlexBuilderfrom
http://www.adobe.com/go/flex_trial.Theeasiest
waytodothisistogetthestandaloneinstallation
(evenifyoualreadyhaveEclipseinstalledforsome
otherpurpose).ThereisalsoanEclipsepluginifyou
aresoinclined.Note:Wedonotprovide
downloadablesourcecodeforthisbook,becausethe
examplesaresmallandyoulearnalotbywriting
themwithinFlexBuilder.

DisplayaLabel

SelectFile|New|Other.Thisbringsupthe
Selectawizarddialogbox.

OpenFlexBuilderandselectFlexProject.
ThisbringsuptheNewFlexProjectDialog
box.

Typeinaprojectname:helloWorld.

Usethedefaultlocation(whichwillalready
bechecked).

SelectWebapplication(runsinFlash
Player).

Leaveeverythingelsealoneandpress
Finish.

YourprojectwillopenintheMXMLcodeeditor.You
willseethefiletitledhelloWorld.mxml.Notethat
thisisavalidXMLfile.

NowaddanXMLtaginbetweentheApplica
tiontags:
<mx:Labeltext="Hello,world"/>

ThisinsertsaLabelcomponentintoyourFlex
application,whichshouldnowlooklikethe
following:
<?xmlversion="1.0"encoding="utf8"?>
<mx:Applicationname="helloWorld"
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute">
<mx:Labeltext="Hello,world"/>
</mx:Application>

FlexBuilderautomaticallyputsinthefirstlinethat
youseeinthelistingabove;thisisthedoctypeline
whichspecifiesthatthisisastandardXMLfile.
However,Flexignoresthislinewhencompilingthe
programandsoweshallleaveofftheredundant
doctypedeclarationthroughouttherestofthebook.
Hint:YoucaneasilyaccesstheActionScript
documentationforagivenobjectinFlexBuilder
bypressingShiftF2whenyourcursorisona
component.
ThenamepropertyintheApplicationtagisnot
insertedbyFlexBuilderandisignoredbyFlex;we
useittogivethenameofthefilecontainingthe
program.Inthiscase,thefullfilenameis
helloWorld.mxml.
Nowruntheapplication.GototheRunmenuand
selectRun.(IfyoupokearoundinFlexBuilder
youllfindothershortcutstorunningapplications).
Thisshouldlaunchyourwebbrowserandrunthe
applicationwithinthebrowser.Youllseethewords
Hello,worldinafieldofblue.
NotethatHello,worldisintheupperleftcorner.
ModifytheApplicationtagbyremovingthe
layout="absolute"propertyandrerunthe
8

FirstStepsinFlex

application.YoullseethatHello,worldisnow
centered.
Inmostoftheexamplesinthisbookwewillremove
thelayoutproperty.IntheContainerschapterwell
gointomoredetailaboutwhatthatpropertydoes.
Note:MXMLallowsyoutodescribeandconfigure
componentsinahighlevel,declarativefashion.
However,MXMLisalwaystranslatedintothe
ActionScriptlanguage,whichisthencompiledintoa
filewithanextensionof.swf,forShockwaveFlash.
TheseSWFfilescontainbytecodethatisexecutedby
theActionScriptVirtualMachine(AVM).

DataBinding
CreateanewapplicationcalledhelloWorld2,and
removethelayoutproperty.Placeyourcursor
withintheApplicationbodyandaddaStringanda
Labelcomponent.Notethatwhenyouenter<and
thenstarttyping,forexample,String,FlexBuilder
willperformcommandcompletionforyou.Make
yourexamplelooklikethis:
<mx:Applicationname="helloWorld2"
xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Stringid="message">Hello,world</mx:String>
<mx:Labeltext="{message}"/>
</mx:Application>

TheStringobject1hasanidproperty.Theidisthe
nameoftheobject,andisnecessarysothatother
objectscantalktoit.Youlluseidalot.
Here,theidismessage,andtheLabelcomponent
usesthisid,butwithincurlybraces.Curlybraces
haveaspecialmeaning,whichisbindtothisother
object.Inthiscase,thetextpropertyintheLabel
objectisfetchedfromtheStringobject.Thatsdata

1Ifyoudontknowwhatobjectsandclassesare,readIntroductionto

Objects,whichyoullfindatwww.FirstStepsInFlex.com.

Hello,World

bindingthedatainoneobjectisboundtothedata
inanother.
Intheaboveexamplethestringdoesntchange
duringtheexecutionoftheprogram.Databindingis
especiallyinterestingwhentheboundtodatadoes
change,becausetheLabelwillbeautomatically
updated.Letslookatamorecomplexexample:
<mx:Applicationname="helloWorld3"
xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:TextInputid="message"text="Hello,world"/>
<mx:Labeltext="{message.text}"/>
</mx:Application>

Nowweveaddedanothercomponent,aTextInput
field.TheLabelstextfieldisboundto
message.text,sowhenyoumodifytheTextInput
thelabelwillautomaticallychange.
Underthecovers,databindinggeneratesfairly
complexcodetowatchforchangesandrespondto
them.Butyoudonthavetothinkaboutthis;allyou
needisthecurlybraces.Thisisoneofmanyplaces
whereFlexdoesalotofworkforyoutokeepyour
lifesimple.

FurtherLearning
SwitchtoDesignView:intheupperleftcorneryoull
seebuttonsthatallowyoutotogglebetween
sourceanddesign.Experimentbyadding
componentstoyourlayoutbydraggingand
droppingthem,thenswitchbacktosourceview
andnoticethatyouvejustaddedmoreMXML
components.Indesignview,tryconfiguringthe
componentsusingtheFlexPropertiespane.Also
explorethedifferentviewswithintheFlex
Propertiespanebyclickingtheiconsintheupper
rightcornerofthatpane.
Note:Wheneveryouseethesymbolinthis
book,itmeansyoushouldgoto
http://www.FirstStepsInFlex.comandtypethe
10

FirstStepsinFlex

wordtotherightoftheintothesearchbox
theretofindoutmoreinformationaboutthat
topic.
Thereareanumberofonlinecommunitiesoutthere
tohelpansweryourquestionsaboutFlex:
FlexcodersYahooGroup:Flexcoders
AdobeForums:AdobeForums
Blogsarealsoagreatwaytocontinuelearning
aboutFlex.http://feeds.adobe.comhasaFlex
categorywhichmakesfindingFlexblogseasy.

Hello,World

11

You might also like