background image

Creating and Extending 

Fl

ex 2 Components

Ad

ob

e

®

 

Fl

e

x

 

2

Содержание FLEX 2 - CREATING AND EXTENDING COMPONENTS

Страница 1: ...Creating and Extending Flex 2 Components Adobe Flex 2...

Страница 2: ...by the Apache Software Foundation http www apache org Macromedia Flash 8 video is powered by On2 TrueMotion video technology 1992 2005 On2 Technologies Inc All Rights Reserved http www on2 com This pr...

Страница 3: ...er 4 Creating Custom Events 35 About events 35 Dispatching custom events 38 Chapter 5 Using Metadata Tags in Custom Components 45 About metadata tags 46 Metadata tags 49 Chapter 6 Compiling Components...

Страница 4: ...vanced Visual Components in ActionScript 147 About creating advanced components 147 Implementing the component 155 Making components accessible 170 Adding version numbers 171 Best practices when desig...

Страница 5: ...custom validators 217 Example Creating a simple validator 219 Example Validating multiple fields 222 Chapter 15 Creating Effects 227 About creating a custom effect 228 About tween effects 237 Writing...

Страница 6: ...6 Contents...

Страница 7: ...ing Flex or have read Getting Started with Flex 2 Getting Started with Flex 2 provides an introduction to Flex and helps you develop the basic knowledge that makes using this manual easier Creating an...

Страница 8: ...w of Flex features and application development procedures Flex 2 Developer s Guide Describes how to develop your dynamic web applications Creating and Extending Flex 2 Components Describes how to crea...

Страница 9: ...s The following typographical conventions are used in this book Italic font indicates a value that should be replaced for example in a folder path Code font indicates code Code font italic indicates a...

Страница 10: ...10 About Flex Documentation...

Страница 11: ...eating custom Adobe Flex components The following topics are included Chapter 2 Creating Flex Components 13 Chapter 3 Using ActionScript to Create Components 25 Chapter 4 Creating Custom Events 35 Cha...

Страница 12: ......

Страница 13: ...Flex class hierarchy to base your custom components on the set of predefined Flex components You can create custom versions of Flex visual controls as well as custom versions of nonvisual components...

Страница 14: ...pplications so that you do not have to duplicate your work Maintainability By developing your application in discrete modules you can isolate and debug errors faster than you could if you developed yo...

Страница 15: ...hy Flex is implemented as an ActionScript class hierarchy That class hierarchy contains component classes manager classes data service classes and classes for all other Flex features The following exa...

Страница 16: ...u create subclasses from the UIComponent class or any other class in the Flex component hierarchy For example if you want to create a component that behaves almost the same as a Button component does...

Страница 17: ...eating custom components is deciding whether to write them in MXML or in ActionScript Ultimately it is the requirements of your application that determine how you develop your custom component N OT E...

Страница 18: ...s a formatter validator or effect use ActionScript To add logging support to your control use ActionScript For more information see Chapter 11 Logging in Building and Deploying Flex 2 Applications For...

Страница 19: ...n you use your custom MXML component The following example shows a possible definition for a custom ComboBox control xml version 1 0 intro StateComboBox mxml Specify the root tag and namespace mx Comb...

Страница 20: ...this case StateComboBox mxml Therefore a file named StateComboBox mxml defines a component with the tag name of namespace StateComboBox As part of the mx Application tag the main application file incl...

Страница 21: ...onents by defining ActionScript classes You can create the following types of components in ActionScript User interface or visual components User interface components contain both processing logic and...

Страница 22: ...directories of your application or for Flex Data Services in the WEB INF flex user_classes directory In this example the package statement specifies that the MyButton as file is in the myComponents su...

Страница 23: ...ou should not try to run the SWF file that is in a SWC file outside of a SWC file To create a SWC file use the compc utility in the flex_install_dir bin directory The compc utility generates a SWC fil...

Страница 24: ...24 Creating Flex Components...

Страница 25: ...ollowing resources Adobe Flex 2 Language Reference Contains the API reference for ActionScript 3 0 Programming ActionScript 3 0 Contains information on using ActionScript 3 0 Contents Using ActionScri...

Страница 26: ...e myFormatters Formatter class definition goes here If you create a component that is shared among multiple applications or a component that might be used with third party components assign a unique p...

Страница 27: ...omponent as part of its implementation as the following example shows package myComponents Import necessary classes import mx core Container import mx controls Button Import all classes in the mx even...

Страница 28: ...inition can have one and only one public class definition although it can have additional private class definitions In a single ActionScript file you can define only one class in the package To define...

Страница 29: ...mport mx controls Button Import all classes in the mx events package import mx events Class definition goes here public class MyButton extends Button Public constructor public function MyButton Call t...

Страница 30: ...public properties you may find it advantageous to define properties by using setter and getter methods For more information see Defining methods on page 32 Defining properties as getters and setters Y...

Страница 31: ...use the identifier value for the name of the argument The variable that stores the property s value cannot have the same name as the getter or setter By convention precede the name of the variables w...

Страница 32: ...ou must include the override keyword and the signature of the method must exactly match that of the superclass method as the following example shows override protected function createChildren void Met...

Страница 33: ...method so the most common pattern is to call super myMethod first in your method override and then add your logic You might need to change something before the superclass method does its work In this...

Страница 34: ...tionScript component the scope is the component itself and not the application or other file that references the component As a result the this keyword inside the component refers to the component ins...

Страница 35: ...er 8 Creating Advanced MXML Components on page 91 For information on creating them for ActionScript components see Chapter 9 Creating Simple Visual Components in ActionScript on page 121 Contents Abou...

Страница 36: ...t flash events Event Event listener for the click event private function handleClick eventObj Event void Define event listener Event listener for the initialize event private function handleInit event...

Страница 37: ...nt instance that is actively processing the Event object The value of this property is different from the value of the target property during the event capture and bubbling phase For more information...

Страница 38: ...event objects is the flash events Event class When you define a custom event you can dispatch an event object of type Event or you can create a subclass of the Event class to dispatch an event object...

Страница 39: ...ed isEnabled Define static constant public static const ENABLE_CHANGED String enableChanged Define a public variable to hold the state of the enable property public var isEnabled Boolean Override the...

Страница 40: ...type package eventType The eventName argument specifies the name including the package of the event The eventType argument specifies the class that defines the event The following example identifies t...

Страница 41: ...a for events is inherited from the superclass however so you do not need to tag events that are already defined with the Event metadata tag in the superclass Dispatching an event You use the dispatchE...

Страница 42: ...ue for the type property var eventObj EnableChangeEvent new EnableChangeEvent enableChangeAgain Because the compiler does not check the value of the type property the only time that your application c...

Страница 43: ...lass EnableChangeEventConst extends Event Public constructor public function EnableChangeEventConst type String isEnabled Boolean false Call the constructor of the superclass super type Set the new pr...

Страница 44: ...ponents MyButtonConst mxml mx Button xmlns mx http www adobe com 2006 mxml click dispatchEvent new EnableChangeEventConst EnableChangeEventConst ENABLE_CHANGED mx Script CDATA import myEvents EnableCh...

Страница 45: ...ol how portions of your code get compiled This topic describes the metadata tags that you use when creating components in MXML and ActionScript Flex 2 Developer s Guide contains information about addi...

Страница 46: ...nds TextArea In this example the Event metadata tag specifies the event name and the class that defines the type of the event object dispatched by the event After you identify the event to the Flex co...

Страница 47: ...he property or method declaration In an ActionScript file when you define component events or other aspects of a component that affect more than a single property you add the metadata tag outside the...

Страница 48: ...a mx Script CDATA Import Event class import flash events Event Define class properties and methods private var _enableTA Boolean Add the Inspectable metadata tag before the individual property Inspect...

Страница 49: ...x as described in Chapter 30 Embedding Assets in Flex 2 Developer s Guide Event Defines the MXML property for an event and the data type of the event object that a component emits For more information...

Страница 50: ...fy String as the allowed data type of the Array elements If a user attempts to assign elements of a data type other than String to the Array in an MXML file the compiler issues a syntax error as the f...

Страница 51: ...setter and a getter method In this case Bindable takes no parameters as the following example shows Bindable public class TextAreaFontControl extends TextArea The Flex compiler automatically generates...

Страница 52: ...tected or private property defined by a getter or setter method You must define both a setter and a getter method to use the Bindable tag with the property If you define just a setter method you creat...

Страница 53: ...t can be used as the sources for data bindings Define public vars for tracking font size Bindable public var maxFontSize Number 15 Bindable public var minFontSize Number 5 In the following example you...

Страница 54: ...that you defined by using setter and getter methods Using read only properties as the source for data binding You can automatically use a read only property defined by a getter method which means no...

Страница 55: ...rtyName The propertyName property specifies the name of the default property You can use the DefaultProperty metadata tag in your ActionScript component to define a single default property For more in...

Страница 56: ...fine the effect Effect name darkenEffect event darken class ModalText extends TextArea In an MXML file you can define the event and effect in an mx Metadata block as the following example shows mx Met...

Страница 57: ...n ActionScript component can dispatch Event name myEnableEvent type flash events Event public class MyComponent extends UIComponent The following example shows the Event metadata tag in the mx Metadat...

Страница 58: ...operty that you want to add such as enumeration values or that a String property represents a file path then add the Inspectable metadata tag with that information Code hints for components and the in...

Страница 59: ...ecifies which inspectable properties should not be allowed none which are used only for Flex Builder Flash and which are used only by Flex and not Flex Builder MXML format String Determines the type o...

Страница 60: ...ype package className You must specify a fully qualified package and class name NonCommittingChangeEvent metadata tag The NonCommittingChangeEvent metadata tag identifies an event as an interim trigge...

Страница 61: ...omponent Bindable event valueCommit NonCommittingChangeEvent change function get text String return getText function set text t void setText t Dispatch events Style metadata tag Use the Style metadata...

Страница 62: ...ecify type uint you might set format Color if the style defines an RGB color enumeration String Specifies an enumerated list of possible values for the style property inherit String Specifies whether...

Страница 63: ...as MXML and ActionScript files as SWC files or as Runtime Shared Libraries RSLs This topic describes the options you have when you compile components Contents About compiling 63 Compiling components w...

Страница 64: ...the Flex Compilers in Building and Deploying Flex 2 Applications and Chapter 10 Building Projects in Using Flex Builder 2 This section presents some examples of using the mxmlc compiler The most basic...

Страница 65: ...duce a SWF file 2 Caches the compiled SWF file on the server 3 Returns the SWF file to the client About case sensitivity during a compilation The Flex compilers use a case sensitive file lookup on all...

Страница 66: ...e classpath is based on the order of the directories listed in the classpath An ActionScript component in a subdirectory of a directory included in the classpath must define a fully qualified package...

Страница 67: ...an archive file of Flex components SWC files make it easy to exchange components among Flex developers You need to exchange only a single file rather than the MXML or ActionScript files images and oth...

Страница 68: ...you specify the directory location of an RSL file by using one of the following methods Flex Builder Open the Project Properties dialog box and then select Flex Build Path to set the library directori...

Страница 69: ...ript file you refer to it in one of the following ways If you store the formatter component in the same directory as the application file or in a directory that the ActionScript classpath not a subdir...

Страница 70: ...r the application subdirectory If you store the formatter component in a subdirectory of the ActionScript classpath directory you specify that subdirectory as part of the package statement as the foll...

Страница 71: ...to create the SWC file for this component compc source path c flex myComponentsForSWCs include components myComponents formatters MySimpleFormatter o c flex mainApp MyFormatterSWC swc In this example...

Страница 72: ...2 Applications Compiling components with Flex Data Services If you have Adobe Flex Data Services you can compile your application and any custom components in the same way that you can when using Fle...

Страница 73: ...file to the WEB INF flex user_classes directory or to any directory specified by the library path tag in the flex config xml file When you deploy the SWC file ensure that the corresponding MXML or Ac...

Страница 74: ...74 Compiling Components...

Страница 75: ...eating MXML Components This part describes how to create custom Flex components in MXML The following topics are included Chapter 7 Creating Simple MXML Components 77 Chapter 8 Creating Advanced MXML...

Страница 76: ......

Страница 77: ...MXML components 77 Scoping in custom components 83 Applying styles to your custom component 84 About MXML components In typical Flex applications you do not code the entire application within a single...

Страница 78: ...on file which contains the mx Application root tag and references one or more components that are defined in separate MXML and ActionScript files Each MXML component extends an existing Flex component...

Страница 79: ...yComp as part of the mx Application tag This namespace definition specifies the location of the MXML component In this case it specifies that the component is in the same directory as the main applica...

Страница 80: ...bj Event void myTA text foo mx Script local StateComboBox rowCount 5 close handleCloseEvent event mx TextArea id myTA mx Application MXML components and ActionScript classes When you create a custom M...

Страница 81: ...the mx FormItem tags contains a reference to the MyComp StateComboBox tag that you created in Creating MXML components on page 78 xml version 1 0 mxml AddressForm mxml mx Form xmlns mx http www adobe...

Страница 82: ...t mx FormItem MyComp EmptyForm mx Application The AddressForm mxml file specifies the Form container as its root tag Because you define a container as the root tag of the MXML component you are creati...

Страница 83: ...then use those new properties to pass configuration information to the component children For more information see Chapter 8 Creating Advanced MXML Components on page 91 Scoping in custom components S...

Страница 84: ...x ComboBox This example defines an event listener for the ComboBox control that updates the stateIndex property when the ComboBox control closes Applying styles to your custom component Along with ski...

Страница 85: ...er 18 Using Styles and Themes in Flex 2 Developer s Guide For information on creating custom styles see Chapter 11 Creating Custom Style Properties on page 183 Applying styles from the custom componen...

Страница 86: ...defines styles for the open duration and font size application developers can still specify font color or other styles The following example uses StateComboBoxWithStyleProps mxml in an application and...

Страница 87: ...ing example shows xml version 1 0 mxml MainStyleOverrideUsingClassSel mxml mx Application xmlns mx http www adobe com 2006 mxml xmlns MyComp myComponents mx Style myStateComboBox openDuration 1000 mx...

Страница 88: ...Comp myComponents mx Style StateComboBoxWithStyleProps openDuration 1000 mx Style MyComp StateComboBoxWithStyleProps mx Application In this example the type selector specifies the openDuration style f...

Страница 89: ...ain application file that style definition is also applied to any custom component that uses a ComboBox control as its root tag as the following example shows xml version 1 0 mxml MainStyleOverrideUsi...

Страница 90: ...xml MainStyleOverrideUsingCBTypeSelConflict mxml mx Application xmlns mx http www adobe com 2006 mxml xmlns MyComp myComponents mx Style ComboBox color red openDuration 1000 fontSize 15 StateComboBoxW...

Страница 91: ...nent 92 Working with events 107 About interfaces 114 About reusable MXML components One design consideration when you create custom MXML components is reusability That is do you want to create a compo...

Страница 92: ...o create ActionScript classes When defining classes you use class properties to store information and class methods to define class functionality When creating MXML components you can also add propert...

Страница 93: ...tag becomes a method of the component In the following example the component defines two data providers to populate the ComboBox control and a function to use as the event listener for the creationCo...

Страница 94: ...takes a single argument that specifies the value of the shortNames property xml version 1 0 mxmlAdvanced myComponents StateComboBoxPropMethod mxml mx ComboBox xmlns mx http www adobe com 2006 mxml cr...

Страница 95: ...t specify an id which becomes the property name Optionally you can specify an initial value in the body of the tag or you can use the source property to specify the contents of an external URL or file...

Страница 96: ...gth void if shortNames dataProvider stateArrayShort else dataProvider stateArrayLong mx Script mx ComboBox In the preceding example you implement the StateComboBox mxml file by using the mx Boolean ta...

Страница 97: ...on set shortNames val Boolean void Call method to set the dataProvider based on the name length __shortNames val if __shortNames this dataProvider stateArrayShort else this dataProvider stateArrayLong...

Страница 98: ...Names true mx Button click myStateCB shortNames myStateCB shortNames mx Application In this example selecting the button toggles the display format of the state name between the short and long formats...

Страница 99: ...an MXML tag such as mx Boolean and any ActionScript property defined as a variable or defined by using setter and getter methods as the destination of a binding expression For example Defining propert...

Страница 100: ...t shortNames val Boolean void __shortNames val if __shortNames dataProvider stateArrayShort else dataProvider stateArrayLong Create and dispatch event dispatchEvent new Event changeShortNames Include...

Страница 101: ...e component by using public properties of the component Supporting data binding in custom properties on page 99 describes how to define properties for MXML components by using MXML and ActionScript an...

Страница 102: ...the parentDocument property see Chapter 14 Using the Application Container on page 571 in Flex 2 Developer s Guide Even if the calling file does not pass a reference to the Application object you can...

Страница 103: ...CloseEvent event mx Script CDATA import flash events Event import mx core Application public function handleCloseEvent eventObj Event void mx core Application application myTAMain text String this sel...

Страница 104: ...ml mx ComboBox xmlns mx http www adobe com 2006 mxml close handleCloseEvent event mx Script CDATA import flash events Event public function handleCloseEvent eventObj Event void parentDocument myTAMain...

Страница 105: ...the main application other than that it writes its results back to a TextArea control as the following example shows xml version 1 0 mxmlAdvanced myComponents StateComboBoxPassRefToTA mxml mx ComboBox...

Страница 106: ...alling component to the custom MXML component as the following example shows xml version 1 0 mxmlAdvanced CallingComponent mxml mx Application xmlns mx http www adobe com 2006 mxml horizontalAlign lef...

Страница 107: ...tions are event driven Events let a programmer know when the user interacts with the interface and also when important changes happen in the appearance or life cycle of a component such as the creatio...

Страница 108: ...ose handleCloseEvent event mx Application In this example if the MXML component dispatches a close event the event listener in the calling MXML file handles it Alternatively you could define the event...

Страница 109: ...mple you define a new component called TextAreaEnabled mxml that uses a mx TextArea tag as its root tag This component also defines a new property called enableTA that users set to true to enable text...

Страница 110: ...lash events Event mx Metadata mx Script CDATA import flash events Event Define private variable to hold the enabled state private var __enableTA Boolean Define a setter method for the private variable...

Страница 111: ...id myButton label Click to enable click myTA enableTA myTA enableTA mx Application If you do not use the Event metadata tag in the custom component file to define the enableChanged event the MXML com...

Страница 112: ...an event that a child of the root container dispatches you can handle it in the MXML component in the same way as you handle an event from the root container However if a child component of the root c...

Страница 113: ...events Event mx Metadata mx Script CDATA import flash events Event Redispatch event private function handleCloseEventInternal eventObj Event void dispatchEvent eventObj mx Script mx FormItem label Nam...

Страница 114: ...void myTA text eventObj type mx Script mx TextArea id myTA mx TextArea id myTAClose MyComp AddressForm mouseDown handleMouseDown event close handleCloseEvent event mx Application About interfaces Inte...

Страница 115: ...component implements the SuperBox interface xml version 1 0 StateComboBox mxml mx ComboBox xmlns mx http www adobe com 2006 mxml implements SuperBox mx Script CDATA public function selectSuperItem Str...

Страница 116: ...event listener for the preinitialize initialize or creationComplete event to replace the constructor These events are all defined by the UIComponent class and inherited by all of its subclasses If yo...

Страница 117: ...com 2006 mxml xmlns MyComp myComponents creationComplete initApp mx Script CDATA public function initApp void myTA text myFC x String myFC x mx Script MyComp ObjectComp id myFC x 1 y 2 z 3 mx TextAre...

Страница 118: ...118 Creating Advanced MXML Components...

Страница 119: ...e Flex components in ActionScript The following topics are included Chapter 9 Creating Simple Visual Components in ActionScript 121 Chapter 10 Creating Advanced Visual Components in ActionScript 147 C...

Страница 120: ......

Страница 121: ...rchy For information on creating advanced components in ActionScript see Chapter 10 Creating Advanced Visual Components in ActionScript on page 147 Contents About ActionScript components 121 Adding pr...

Страница 122: ...n class and then modify it in your custom class This topic describes how to create simple ActionScript components Simple components are subclasses of existing Flex components that modify the behavior...

Страница 123: ...DeleteTextArea Call super super Add event listener for keyDown event addEventListener keyDown myKeyDown Define private keyDown event handler private function myKeyDown eventObj KeyboardEvent void Che...

Страница 124: ...hen you create a subclass of a Flex class In the previous example you could have named your custom component TextArea and written it to the TextArea as file in the myComponents directory as the follow...

Страница 125: ...MXML All public properties defined in your component are accessible in MXML by using MXML tag properties For example you might allow the user to pass a value to your component as the following example...

Страница 126: ...c such as dispatching an event You can define and initialize a private variable as the following example shows private var _prop2 Number 5 When you specify a value to the property in MXML Flex automat...

Страница 127: ...teners addEventListener keyDown myKeyDown addEventListener creationComplete myCreationComplete Define private var for current font size private var currentFontSize Number Define a public property for...

Страница 128: ...ont size maxFontSize and minimum font size minFontSize of the control Users can set these properties in MXML as the following example shows xml version 1 0 as MainTextAreaFontControl mxml mx Applicati...

Страница 129: ...addEventListener keyDown myKeyDown addEventListener creationComplete myCreationComplete private var currentFontSize Number public var minFontSize Number 5 Define private variable for maxFontSize publ...

Страница 130: ...od checks that the specified font size is less than the predefined limit of 30 pixels If the font size is greater than the limit it sets it to the limit Creating a default property You can define a de...

Страница 131: ...to the value of the default property public function set defaultText value String void if value null text value public function get defaultText String return text In this example you add a new propert...

Страница 132: ...You can also use the Inspectable metadata tag with setter and getter methods For more information see Chapter 5 Using Metadata Tags in Custom Components on page 45 Using data binding with custom prope...

Страница 133: ...perty when the source property changes However in order to signal to Flex to perform the copy you must register the property with Flex and the source property must dispatch an event To register a prop...

Страница 134: ...source for data bindings Define public properties for tracking font size Bindable public var maxFontSize Number 15 Bindable public var minFontSize Number 5 If you omit the event name from the Bindable...

Страница 135: ...AreaFontControlBinding super addEventListener keyDown myKeyDown addEventListener creationComplete myCreationComplete private var currentFontSize Number public var minFontSize Number 5 Define private v...

Страница 136: ...Size break default break In this example the setter updates the value of the property and then dispatches an event to trigger an update of any data binding destination The name of the event is not res...

Страница 137: ...n HBoxWithAlert super Define the override override public function addChild child DisplayObject DisplayObject Call super addChild super addChild child Open the Alert box Alert show Item added successf...

Страница 138: ...mx Application xmlns mx http www adobe com 2006 mxml xmlns MyComp myComponents mx Script CDATA import mx controls Button public function addButton void var myButton Button new Button myButton label N...

Страница 139: ...put TextInput public function MyPanel super Copy the text from one child component to another public function xfer void myOutput text myInput text In this example the MyPanel component defines two var...

Страница 140: ...inherited property must be writable If you try to initialize a constant or a property defined by a getter method without a corresponding setter method the Flex compiler issues an error The data type...

Страница 141: ...onComplete eventObj Event void Define event listener mx Script MyComp MyButton click handleClick event creationComplete handleCreationComplete event mx Application Your custom components can also defi...

Страница 142: ...stom events and use the predefined events You use custom events to support data binding to respond to user interactions or to trigger actions by your component For an example that uses events to suppo...

Страница 143: ...rivate function enableChangedListener eventObj Event void Handle event In this example the public method enableInput lets the user enable or disable input to the control When you call the enableInput...

Страница 144: ...ged event Event void myTA text Got Event mx Script MyComps ModalTextEvent id myMT enableChanged handleEnableChanged event mx Button click myMT enableInput true mx TextArea id myTA mx Application Apply...

Страница 145: ...n control with the default color and borderColor styles set in your component s class file xml version 1 0 as MainBlueButton mxml mx Application xmlns mx http www adobe com 2006 mxml xmlns MyComps myC...

Страница 146: ...n set the font face font size and other style properties For more information on the available style properties see Flex 2 Developer s Guide You can also define new style properties for your component...

Страница 147: ...About creating advanced components Simple visual components are subclasses of existing Flex components that modify the appearance of the component by using skins or styles or add new functionality to...

Страница 148: ...ur at the same time or to ensure that properties are set in a specific order For more information see Implementing the commitProperties method on page 158 createChildren Creates any child components o...

Страница 149: ...t size of a component much faster than Flex can update the layout of an application Therefore you only want to update the layout after you are sure that you determined the final value of the font size...

Страница 150: ...d examples see Implementing the commitProperties method on page 158 About the component instantiation life cycle The component instantiation life cycle describes the sequence of steps that occur when...

Страница 151: ...figure the button control b label Submit Component setter methods might call the invalidateProperties invalidateSize or invalidateDisplayList methods 3 You call the addChild method to add the componen...

Страница 152: ...r the last render event occurs Flex performs the following actions a Makes the component visible by setting the visible property to true b Dispatches the creationComplete event on the component The co...

Страница 153: ...more information see Chapter 9 Creating Simple Visual Components in ActionScript on page 121 c Embed any graphic and skin files For more information see Chapter 9 Creating Simple Visual Components in...

Страница 154: ...f components into discrete elements so that they can be implemented piece by piece For example to make your component focusable it must implement the IFocusable interface to let it participate in the...

Страница 155: ...Indicates that a component or object can use the invalidation mechanism to perform delayed rather than immediate property commitment measurement and drawing or layout ILayoutManagerClient Indicates th...

Страница 156: ...page 166 Basic component structure The following example shows the basic structure of a Flex component package myComponents public class MyComponent extends UIComponent You must define your ActionScri...

Страница 157: ...he createChildren method Implementing the createChildren method A component that creates other components or visual objects within it is called a composite component For example the Flex ComboBox cont...

Страница 158: ...component You must call the addChild method for each child object After you create a child component you can use properties of the child component to define its characteristics In this example you cre...

Страница 159: ...t alignText t String void _alignText t bAlignTextChanged true Trigger the commitProperties measure and updateDisplayList methods as necessary In this case you do not need to remeasure the component in...

Страница 160: ...operties method you can reduce unnecessary processing overhead To coordinate multiple modifications to the same property You do not necessarily want to perform a complex calculation every time a user...

Страница 161: ...anged true invalidateProperties invalidateDisplayList Implement the commitProperties method override protected function commitProperties void super commitProperties Check whether the flags indicate a...

Страница 162: ...subclass of an existing component you might implement the measure method only if you are performing an action that requires modification to the default sizing rules defined in the superclass Therefor...

Страница 163: ...x controls Button public class BlueButton extends Button public function BlueButton super override protected function measure void super measure measuredWidth 100 measuredMinWidth 50 measuredHeight 50...

Страница 164: ...f the button the button uses its minimum width Calculating default sizes The example in Implementing the measure method on page 162 uses static values for the default size and default minimum size of...

Страница 165: ...a 10 pixel border area around the text measuredWidth measuredMinWidth lineMetrics width 10 measuredHeight measuredMinHeight lineMetrics height 10 For text strings that are longer than the display area...

Страница 166: ...utChrome method to define and position the border area of the container and any additional elements that you want to appear in the border area For example the Panel container uses the layoutChrome met...

Страница 167: ...DisplayList method uses the settings of the icon and labelPlacement properties to control the display of the button For containers that have child controls the updateDisplayList method controls how th...

Страница 168: ...Box container lays out its children from the top of the container to the bottom of the container in the order in which the children are added to the container The following example overrides the updat...

Страница 169: ...the y coordinate of the child plus the vertical gap between children This is used to calculate the coordinate of the next child yOfComp yOfComp gap In this example you use the UIComponent move method...

Страница 170: ...te graphics property specifies a Graphics object that you can use to add vector drawings to your component For example in the updateDisplayList method you can use methods of the Graphics class to draw...

Страница 171: ...on about accessibility see Chapter 36 Creating Accessible Applications in Flex 2 Developer s Guide Adding version numbers When releasing components you can define a version number This lets developers...

Страница 172: ...cludes a button and a text field or a component that includes a button a text field and a validator When you create composite components you should instantiate the controls inside the component s clas...

Страница 173: ...if mode_mc mode_mc new Button mode_mc addEventListener click handleClickEvent addChild mode_mc The createChildren method also contains a call to the addEventListener method to register an event liste...

Страница 174: ...Creating the ModalText component The following code example implements the class definition for the ModalText component The ModalText component is a composite component that contains a Button control...

Страница 175: ...Changed event to determine when the ModalText textPlacement property is modified as the following example shows xml version 1 0 asAdvanced MainModalTextEvent mxml mx Application xmlns mx http www adob...

Страница 176: ...sh events Event a Extend UIComponent public class ModalText extends UIComponent b Implement the class constructor public function ModalText super c Define variables for the two child components Declar...

Страница 177: ...available comment out these lines mode_mc setStyle overSkin modeOverSkinName mode_mc setStyle upSkin modeUpSkinName mode_mc setStyle downSkin modeDownSkinName mode_mc addEventListener click handleCli...

Страница 178: ...setting of the textPlacement property override protected function updateDisplayList unscaledWidth Number unscaledHeight Number void super updateDisplayList unscaledWidth unscaledHeight Subtract 1 pixe...

Страница 179: ...for the textPlacement property public function set textPlacement p String void _textPlacement p invalidateDisplayList dispatchEvent new Event placementChanged The textPlacement property supports data...

Страница 180: ...moving the SWC file to the same directory as the MXML file and setting the namespace to as the following example shows mx Application xmlns mx http www adobe com 2006 mxml xmlns For more information...

Страница 181: ...correctly The following example adds a static variable to tell the linker that class A must be initialized before class B public class A static function foo Number return 5 public class B static funct...

Страница 182: ...182 Creating Advanced Visual Components in ActionScript...

Страница 183: ...x components through style properties These properties can define the size of a font used in a Label control or the background color used in the Tree control In Flex some styles are inherited from par...

Страница 184: ...roperty In general color and text styles support CSS inheritance regardless of whether they are set by using CSS or style properties All other styles do not support CSS inheritance unless otherwise no...

Страница 185: ...operty on a component For example the following code creates a TextArea control then sets the backgroundColor style of the component to blue 0x0000FF var myTA TextArea new TextArea myTA setStyle backg...

Страница 186: ...undColor true invalidateDisplayList return The styleChanged method first calls superclass s styleChanged method to let the superclass handle the style change After the superclass gets a call to handle...

Страница 187: ...e updates to the updateDisplayList method the updateDisplayList method has to perform only the updates based on the style changes it may not have to redraw or recalculate the appearance of the entire...

Страница 188: ...le By default use the style defined by the CSS type selector MyComp StyledRectangle id mySR1 By default use the style defined by the CSS type selector MyComp StyledRectangle id mySR2 Change the defaul...

Страница 189: ...metadata tag the MXML compiler issues a syntax error when you try to set the property as an MXML tag attribute The Style metadata tag has the following syntax Style name style_name property value For...

Страница 190: ...omponent Define a static variable private static var classConstructed Boolean classConstruct Define a static method private static function classConstruct Boolean if StyleManager getStyleDeclaration S...

Страница 191: ...tyleProp String void super styleChanged styleProp Check to see if style changed if styleProp fillColors bFillColorsChanged true invalidateDisplayList return Override updateDisplayList to update the co...

Страница 192: ...et a default value for a style property is to define a static initializer in your component A static initializer is executed once the first time Flex creates an instance of a component In Defining a s...

Страница 193: ...y using style properties The mechanism for creating style properties to support skinning is the same as for creating other style properties Setting a style property for a skin that triggers a call to...

Страница 194: ...194 Creating Custom Style Properties...

Страница 195: ...t user must then pass a value that exactly matches the property s data type or else Flex issues a compiler error A template component is a component in which one or more of its properties is defined w...

Страница 196: ...op component MyComp topRow MyComp bottomRow mx Button label Button 1 mx Button label Button 2 mx Button label Button 3 MyComp bottomRow MyComp MyTemplateComponent mx Panel mx Application The MyTemplat...

Страница 197: ...is a TextArea control and the bottom components are two LinkButton controls Implementing a template component The section About template components on page 195 shows an example of a template component...

Страница 198: ...Array private function init void Add the top component to the VBox container addChild topRow Create an HBox container This container is the parent container of the bottom row of components var contro...

Страница 199: ...er 6 Improving Startup Performance in Building and Deploying Flex 2 Applications You can create a template component that also takes advantage of deferred creation Rather than having Flex create your...

Страница 200: ...mx core IDeferredInstance public var bottomRow Array private function init void Add the top component to the VBox container Cast the IDeferredInstance object to UIComponent so that you can add it to t...

Страница 201: ...es using the IDeferredInstance interface This section describes how to define component properties of type IDeferredInstance Defining a generic property To define a generic property one with no associ...

Страница 202: ...rrayElementType mx core IDeferredInstance public var bottomRow Array Define an Array of deferred properties for a row of components Restrict the type of the component to mx controls Button InstanceTyp...

Страница 203: ...mx http www adobe com 2006 mxml initialize init mx Script CDATA import mx containers HBox import mx core UIComponent InstanceType mx controls Label public var topRow IDeferredInstance Define an Array...

Страница 204: ...204 Creating Template Components...

Страница 205: ...nts This part describes how to create formatter validator and effect components for Adobe Flex The following topics are included Chapter 13 Creating Custom Formatters 207 Chapter 14 Creating Custom Va...

Страница 206: ......

Страница 207: ...he functionality of these predefined formatters or create formatters for your specific application needs This topic describes how to create a custom data formatter For more information on using format...

Страница 208: ...ontain a public format method that takes a single argument and returns a String that contains the formatted data Most of the processing of your custom formatter occurs within the format method Your cu...

Страница 209: ...ic class SimpleFormatter extends Formatter Declare the variable to hold the pattern string public var myFormatString String upper Constructor public function SimpleFormatter Call base class constructo...

Страница 210: ...is in the myFormatters subdirectory of the application or in the default classpath of the application For more information on deploying your formatters see Chapter 6 Compiling Components on page 63 H...

Страница 211: ...formatString property of the SwitchSymbolFormatter class to specify the format string You can mix alphanumeric characters and placeholder characters in this format string The format string can contai...

Страница 212: ...matters Formatter import mx formatters SwitchSymbolFormatter public class CustomSSFormatter extends Formatter Declare the variable to hold the pattern string public var formatString String Constructor...

Страница 213: ...ue The following example uses this custom formatter in an application xml version 1 0 encoding UTF 8 formatters formatterSS mxml mx Application xmlns mx http www adobe com 2006 mxml xmlns MyComp myFor...

Страница 214: ...he data package myFormatters formatters myFormatter ExtendedZipCodeFormatter as import mx formatters Formatter import mx formatters ZipCodeFormatter import mx formatters SwitchSymbolFormatter public c...

Страница 215: ...d in its base class ZipCodeFormatter The following example uses this custom formatter in an application xml version 1 0 encoding UTF 8 formatters FormatterZC mxml mx Application xmlns mx http www adob...

Страница 216: ...216 Creating Custom Formatters...

Страница 217: ...in a user interface might or might not be appropriate for the application In Flex you use a validator to ensure the values in the fields of an object meet certain criteria For example you can use a va...

Страница 218: ...tion error To disable this verification set this property to false In the doValidation method of your validator class you typically call the base class s doValidation method to perform the verificatio...

Страница 219: ...thod to programmatically invoke a validator from within a Flex application However you should never override this method in your custom validator classes You need to override only the doValidation met...

Страница 220: ...t Array Convert value to a Number var inputValue Number Number value Clear results Array results Call base class doValidation results super doValidation value Return if there are errors if results len...

Страница 221: ...e 222 You can use this validator in your Flex application as the following example shows xml version 1 0 validators MainAgeValidator mxml mx Application xmlns mx http www adobe com 2006 mxml xmlns MyC...

Страница 222: ...you use a NameValidator that validates an item that contains three fields named first middle and last xml version 1 0 validators MainNameValidator mxml mx Application xmlns mx http www adobe com 2006...

Страница 223: ...fName String value first var mName String value middle var lName String value last Clear results Array results Call base class doValidation results super doValidation value Return if there are errors...

Страница 224: ...ields of the Object passed to the validator you include the optional second argument to the constructor for the ValidationResult class to specify the subfield that caused the validation error This inc...

Страница 225: ...idation private var results Array public function NameValidatorAllFields super override protected function doValidation value Object Array var fName String value first var mName String value middle va...

Страница 226: ...eturn results Notice that you remove the return statement from the body of the if statements so that the method contains only a single return statemen This modification allows you to detect three diff...

Страница 227: ...e measured in milliseconds For example you can use behaviors to cause a dialog box to bounce slightly when it receives focus or to slowly fade in when it becomes visible Adobe Flex supplies a number o...

Страница 228: ...image shows the class hierarchy for effects Defining factory and instance classes To define a custom effect you create two classes the factory class and the instance class Factory class The factory cl...

Страница 229: ...or FadeInstance About the effect base classes You define effects by creating a subclass from the effects class hierarchy Typically you create a subclass from one of the following classes mx effects Ef...

Страница 230: ...ce method Effect getAffectedProperties Required Returns an Array of Strings where each String is the name of a property of the target object that is changed by this effect If the effect does not modif...

Страница 231: ...implement this method For more information see Overriding the initEffect method on page 250 TweenEffectInstance onTweenUpdate Required Use when you create a subclass from TweenEffectInstance A callbac...

Страница 232: ...nction MySound targetObj Object null Call base class constructor super targetObj Set instanceClass to the name of the effect instance class instanceClass MySoundInstance This effect modifies no proper...

Страница 233: ...port flash media Sound public class MySoundInstance extends EffectInstance Embed the MP3 file Embed source sample mp3 Bindable private var sndCls Class Define local variables private var snd Sound new...

Страница 234: ...way that you reference a standard effect The following example shows an application that uses the MySound effect xml version 1 0 effects MainSoundEffect mxml mx Application xmlns mx http www adobe com...

Страница 235: ...with optional argument public function MySoundParam targetObj Object null Call base class constructor super targetObj Set instanceClass to the name of the effect instance class instanceClass MySoundPa...

Страница 236: ...ects EffectInstance import flash media Sound import flash media SoundChannel import flash net URLRequest public class MySoundParamInstance extends EffectInstance Define local variables private var s S...

Страница 237: ...accepts a start value an end value and an optional easing function When you define tween effect classes you create an instance of the Tween class in your override of the Effect play method The Tween o...

Страница 238: ...otate effect The rotation is controlled by two parameters that are passed to the effect angleFrom and angleTo package myEffects myEffects Rotation as import mx effects TweenEffect import mx effects Ef...

Страница 239: ...n public class RotationInstance extends TweenEffectInstance Define parameters for the effect public var angleFrom Number public var angleTo Number public function RotationInstance targetObj super targ...

Страница 240: ...n In this example you use the effect to rotate an image when the user clicks it Writing an effect for a transition Transitions define how a change of view state appears on the screen You define a tran...

Страница 241: ...In the example in step 1 notice that the Move and Resize effects do not define start values Therefore Flex determines the start values from the current size and position of the effect targets in the c...

Страница 242: ...f transitions to determine the one that matches the change of view state 4 Flex calls the Effect captureStartValues method to initialize propertyChanges start for all effect instances You can also cal...

Страница 243: ...initions for the angleFrom and angleTo property definitions The RotationTransInstance play method determines the default values package myEffects myEffects RotationTrans as import mx effects TweenEffe...

Страница 244: ...the angleFrom property and 360 for the angleTo property The following example shows the RotationTransInstance as class package myEffects myEffects RotationTransInstance as import mx effects effectCla...

Страница 245: ...hanges end rotation 360 Create a Tween object The tween begins playing immediately var tween Tween createTween this angleFrom angleTo duration Override onTweenUpdate method override public function on...

Страница 246: ...3 name y value 110 mx SetProperty target p3 name width value 100 mx SetProperty target p3 name height value 100 mx State mx State name Two mx SetProperty target p2 name x value 110 mx SetProperty targ...

Страница 247: ...e the mouseDown event to specify the event listener that executes when the user selects the component You use the mouseDownEffect trigger to associate an effect with the trigger Suppose that you want...

Страница 248: ...ng public function get bright Boolean return _bright mx Script mx Button When you declare an event in the form Event name eventName type package eventType you can also create a corresponding effect in...

Страница 249: ...id FadeIn duration 1000 alphaFrom 20 alphaTo 1 00 Define custom button that defines the darkenEffect and brightenEffect MyComp MyButton label MyButton id btn darkenEffect FadeOut brightenEffect FadeI...

Страница 250: ...ave to determine the default values at run time In this method you can examine the Event object and the effect target to calculate values at run time For more information on how to create a custom eve...

Страница 251: ...mponents class hierarchy 15 122 compound 172 getters and setters 30 96 composite MXML components 81 compound components 172 constructor about 28 implementing 157 createChildren method 157 creating com...

Страница 252: ...factory class 228 formatters error handling 210 extending 214 formatting data custom 208 ZIP codes 211 G getters 30 96 I IconFile metadata keyword 49 IDeferredInstance interface 199 images Embed meta...

Страница 253: ...defining for custom components 30 96 skins style property 193 startup time RSLs 23 68 static constants 42 Style metadata keyword 49 61 189 styles about 183 custom components 84 144 setting 184 settin...

Страница 254: ...254 Index...

Отзывы: