Nội dung Text: Flex 3 with Java- P2

Chapter 2
To create a TabNavigator control, switchback to the Design mode and follow
these steps:
1. Drag and drop a TabNavigator container from the Navigators section in the
Components view, in the design area.
2. Notice that TabNavigator will be created with one default tab—Tab 1. It can
be seen in the following screenshot:
3. You can add another tab to this container by clicking on the + (the plus sign)
that is displayed above the container. Similarly, use the - (the minus sign) to
delete a tab.
4. Adding a tab will prompt you to enter a new tab label and the type of
container you want to use. Remember the definition of navigator containers:
Navigator container controls user movement, or navigation, among multiple child
containers. These tabs are actual containers, which will be added as children
of the TabNavigator container. For now, I am leaving selection to
default Canvas.
5. Once you click on OK, a new tab will be added to TabNavigator.
You can explore these containers from the Navigators section of the Components
view, as shown in the following screenshot:
[ 37 ]

Introduction to Flex 3 Framework
Form containers
Forms are commonly used containers in the web world. Forms are typically used
to collect user information, such as registration, purchases, billing, and so on. Flex
provides a form-based container with various built-in advantages, such as form
validation, required field indicator, auto-alignment, auto-layout, and so on.
Forms are constructed using the following three types of components:
• Form container - Represents the main Form container
• FormHeading - Represents Form heading
• FormItem - Represents individual control on the Form container, such as text
field, button, and so on
Example of creating a form control:
[ 38 ]

Chapter 2
You can also create forms in the Design view by dragging and dropping Form,
FormHeading located in the Layout section of the Components view, or individual
controls such as TextInput, Button in the Design view. Flex Builder will
automatically add the FormItem tag around the individual control.
In the previous image, A indicates the main Form container; B indicates FormHeader;
and C indicates FormItem. You will also notice the red asterisk (*) symbol
that indicates a mandatory field. You can set a mandatory field by adding the
required="true" property to your FormItem tag.
Constraint-based layout
Flex supports adding a constraint-based layout to relatively arrange components
inside a container. This layout can only be used when the layout property is
set to absolute. I will use the previous form example to demonstrate a
constraint-based layout:
1. Switch to the Design view.
2. Click on the Application area and change the layout property of the
Application tag to absolute from the Flex Properties view, or you can
change it manually from code by switching back to code view.
3. Select the Form container by clicking on its border or selecting the Form node
from the Outline view.
[ 39 ]

Introduction to Flex 3 Framework
4. Now in the Flex Properties view, scroll down to the Layout section. You
will notice that you now see a Constraints preview window with a couple
of checkboxes, as shown in the following screenshot:
5. You can select checkboxes to set constraints. I have selected top and right
constraints, as shown in the following screenshot:
[ 40 ]

Chapter 2
6. Now, the Form container will stay in the top right corner even if you resize
your Flex application window.
Now that you have understood Flex containers and their usage, it's time to dive into
the MXML event model.
Using events in MXML
Events let a developer know when something happens within an application. Events
can be triggered by either user interactions (such as keyboard or mouse clicks), or
they can be system-generated to notify the user that something happened internally
(for example, the application finishes loading, the application closes, and so on). The
event model in Flex provides an excellent way to design loosely-coupled applications
that can consume or dispatch events. This simply means that you can design
components that can perform tasks and notify the outside world by broadcasting one
or more custom events. The event model is broadly based on a well-known design
pattern known as the observer pattern. The observer pattern allows one object,
known as the observer, to watch another object, known as the subject, by registering
a listener(s) for a specific event(s), and then the subject broadcasting event(s) to all
subscribed observers.
For example, you might have two list components where one shows the list of
countries and the other shows the list of states pertaining to the selected country.
In this case, the states list component will listen for any change in the country list
selection and reload itself to show a list of states of the selected country. So, in this
case, the state list component is an observer and the country list component is
a subject.
Events are used to add behavior and actions to your user interface. You can handle
these events in your code by adding event handlers. Event handlers are basically
functions or methods that you write to handle and respond to specific events. They
are also called event listeners.
For listening to specific events from a component, you need to register your event
listener(s) with that component. For example, to listen when an application has
loaded, you can employ a creationComplete event of the Application container.
creationComplete is dispatched by the Application container when it finishes
creating all its children components. You can use this event to initialize variables,
for example.
[ 41 ]

Introduction to Flex 3 Framework
Example of the creationComplete event:
In the code above, you must have noticed a new block. This block is
used in MXML to write ActionScript code. For the time being, ignore the details as
we are going to learn ActionScript and how to use it with MXML in our next chapter.
The important thing to note is that you are using event handler mechanisms to
handle the application's creationComplete to display an alert dialog box. Check
the following example to see how to handle a click event of a Button control:
This time, I have not specified an event handler function on the click event. Instead,
I have written ActionScript code inside the click event block. This is another way to
write event handlers.
The following example will show you how to handle keyboard events:
Example: Keyboard event:
[ 42 ]

Chapter 2
In this example, I added a TextArea control to the application and added an event
handler for the keyUp event. Notice that I am passing the event argument to the
handleKeyUpEvent method. This is known as passing the event reference to the
event handler.
Next, we will see how to handle mouse events in MXML.
An example of mouse events:
In the example above, I registered two mouse events, namely mouseOver and
mouseOut, for the TextArea component. These mouse events will be triggered
when the user moves the mouse over and out of the TextArea control. Try it.
Some of the commonly used mouse and keyboard events are as follows:
Mouse events:
Event Description
mouseUp Dispatches when the user releases the mouse button.
mouseDown Dispatches when the user clicks on the mouse button.
mouseMove Dispatches when the user moves the mouse.
mouseOver Dispatches when the user moves the mouse over a specific
component area.
mouseOut Dispatches when the user moves the mouse out of a specific
component area.
mouseWheel Dispatches when the user scrolls the mouse wheel.
click Dispatches when the user clicks the mouse button.
doubleClick Dispatches when the user double-clicks the mouse button.
[ 43 ]

Introduction to Flex 3 Framework
Keyboard events:
Event Description
keyUp Dispatches when the user releases a key on the keyboard.
keyDown Dispatches when the user presses a key on the keyboard.
You will learn more about events in Chapter 3. To find more information about
various events, visit http://livedocs.adobe.com/flex/3/html/help.
html?content=events_02.html.
Creating custom events
Along with the built-in Flex events, you can also define your own custom events. To
define custom events in MXML, the [Event] metadata tag is used. Metadata tags
provide information to the Flex compiler that describes how your components are
used in a Flex application.
The following is the syntax for the [Event] metadata tag:
[Event(name="eventName", type="package.eventType")]
The eventName argument specifies the name of the event. The eventType argument
specifies the class that defines the event, including the package. Once you define
a custom event using the [Event] metadata tag, this metadata tag makes the
custom event known to the compiler so that it can be referenced into the MXML
component declaration. In simple words, the Flex compiler inserts the necessary
code for enabling your component to register event listeners while compiling your
application. Once you define event metadata, it's your responsibility to dispatch the
event from your component. Flex will not dispatch custom events automatically. To
dispatch any custom event, use the dispatchEvent() method provided by Flex in
the following manner:
dispatchEvent(new Event("eventName"));
You can add event listeners or handlers to custom events in the same way you
did previously:
In the previous example, is a custom component
that defines a custom event called fooEvent. The process of adding event listeners
for custom events is similar to adding listeners to Flex events.
[ 44 ]

Chapter 2
Example:
You will learn more about how to use custom events in custom components later in
the chapter.
By now, you should have a basic understanding of how to lay out your application,
and how to create and handle events in your application. Now, let's understand how
data validation and formatting is done in Flex.
Validating and formatting data
When you are building forms for collecting user information, it's often necessary
to validate the data entered by the user on the client to avoid unnecessary traffic
to the server.
You saw how to add the required field indicators (*) in forms using the required
field property of the FormItem control. However, this does not perform any
validating; this just adds a red asterisk symbol before the field. To perform
validation, you need to implement Flex framework validators.
The Flex framework provides common validators for validating common strings and
number-based data, such as phone number, email address, and so on. The following
list shows the available validators in Flex for common data entry needs:
Validators Description
For validating credit card information
For currency
For validating dates
For validating email addresses
For validating numbers
For validating phone numbers
For validating using Regular Expressions
For validating social security numbers
For validating basic strings
For validating ZIP codes
[ 45 ]

Introduction to Flex 3 Framework
Let's understand the validator syntax:
Validation tag must be the immediate child of MXML file's root tag. Cannot be
defined as the child of any other component inside the root container.
Generally, one validator is created for one field. All validators have the
following properties:
• id—an instance name for the validator
• source—binding to the ID of the field to be validated
• property—the name of the field's property to validate
• required—specifies that a missing or empty value causes a validation error.
It is set to true by default
In the previous example, I added a TextInput control for demonstrating the
validator syntax. Notice that the instance name of email TextInput control is email.
I have used the instance name of TextInput for binding with the property field of
EmailValidator, for example property="{email}". This binding ensures that the
validator is set for validating the email text field. Also notice that the source property
of EmailValidator is set to text, for example source="text". This ensures that
the validator will validate the text property of the email TextInput. It is as good as
saying validate the text property of the email text box. So whatever text you enter in
the email text box will be validated to check if it is a valid email address.
Now that you have understood the general syntax to write validators, it's time to try
one example. I will create a Form control for collecting a user's billing details and
implement email, phone, and number validators. Let's get started.
1. Open the existing Flex project or create a new one.
2. Create the Form control by adding following TextInput fields inside the
FormItem tag:
° First name
° Last name
° Email
° Phone number
[ 46 ]

Chapter 2
° Billing address
° City
° State
° ZIP
° Social security number
3. Make sure that the first name, last name, email, phone number, ZIP, and
social security number fields have the required property set to true.
4. Now, let's start adding validators for each required field immediately after
the tag.
5. Remember to add specific validators for specific fields. For example, use
for the Email field.
6. And that's it. Now run the application and click on every field to focus and
move out of it (to trigger validation).
The code is as follows:
[ 47 ]

Introduction to Flex 3 Framework
ALABAMA
ALASKA
[ 48 ]

Chapter 2
Notice that when you set the focus on any field and move out without typing
anything, it displays a red border around that field:
When you move your mouse over the field, it displays an error message. These are
the default error messages set for every validator. These default error messages can
also be customized by setting the specific validator's error message properties.
In , to change the default error message (This field is
required), set the requiredFieldError property of
(for example, requiredFieldError="Enter email address"). The
requiredFieldError property is derived from the Validator class. Similarly, you
can also set a missingAtSignError property to your own message to change the
error message when users do not enter the @ symbol in the email address. This is
shown in the following screenshot:
The code is as follows:
[ 49 ]

Introduction to Flex 3 Framework
By default, Flex uses the valueCommit event to trigger validations, that is, usually
when components lose their focus. You can change this default behavior by using
the trigger and triggerEvent properties of validator to trigger the validation on
a specific event of a specific object. The trigger property specifies the component
name that is generating the event that triggers the validation. By specifying the event
name in the triggerEvent property, you can instruct the validator as to when to
trigger the validation.
Let's quickly look at how this is done.
You need to add two more properties to the validator. They are:
• trigger—binding to the ID of the object instance that will trigger
the validation
• triggerEvent—The name of the event on the trigger object that will trigger
the validation
Example:
In the previous example, the email validator will be triggered when the user clicks
on the Submit button.
Please go through Flex API documentation for more information on validator-
specific error message properties.
Flex Builder shortcut to open Flex API documentation: Select a
component syntax on which you need help and then press Shift+F2
to open the Flex API documentation.
Restricting user entry
Sometimes while designing user entry forms, you need to restrict the user from
entering certain type of data into the field. For example, you might want to allow
the user to enter only numbers or letters, or a combination of both, and want to
restrict special character entries. This is achieved using the restrict property of
the TextInput field.
[ 50 ]

Chapter 2
The following is an example of restricting the user to enter only numbers and
alphabets, and no special characters:
You can use regular expressions to restrict the user entry in the field. However, this
property only restricts user interaction; the user can put any text into a text field
using ActionScript. To know more about the restrict property and its expression,
see the Flex language reference documentation for the TextInput control.
Formatting
Sometimes the client needs to perform some formatting of raw data in order to
display proper data on screen (such as dates). In Flex, you use formatter classes
to format data into strings.
The Flex framework provides the following different types of formatter classes:
Formatters Description
Used to format currencies
Used to format dates
Used to format numbers
Used to format phone numbesr
Used to format ZIP codes
In the following example, I will use to format raw date
information into a formatted date string. When using DateFormatter, you have
to specify the formatString property. It specifies the appropriate formatting
for the DateFormatter class. For example, MMMM D, YYYY will format the date as
September 18, 2008. To see more pattern strings, go through the language reference
for DateFormatter.
Example of date formatting:
[ 51 ]

Introduction to Flex 3 Framework
The previous example looks like this when you run it:
Before Formatting:
Thu Sep 18 00:43:04 GMT+0530 2008
After Formatting:
September 18, 2008
Similarly, you can also create other formatters, for example, CurrencyFormatter or
PhoneFormatter, and so on.
Notice the [Bindable] and {} curly brackets in the text property.
This is called a Bindable metadata tag and data binding. You will
learn about binding mechanisms in our next section.
Data binding
Data binding is the process of tying the data of one object to another object. This is a
very convenient way to tie data sources with the Flex component without worrying
about how to update components if data source changes dynamically. When you
use data binding, the destination object gets updated automatically if the source
object changes. It may sound very confusing at this point, but let me give you a
simple example.
In the following example, I will use the TextInput and Label controls, and bind
the TextInput control's text property with the Label control's text property. So
whenever you change text in the TextInput control, it will automatically reflect in
the Label control's text property.
[ 52 ]

Chapter 2
Example of data binding:

Introduction to Flex 3 Framework
contactDetails.push({name:"John", phone:"+442768574629",
email:"john@email.com"});
contactDetails.push({name:"Joe", phone:"+445632564367",
email:"joe@email.com"});
contactDetails.push({name:"Steve", phone:"+445632564367",
email:"steve@email.com"});
}
]]>
The labelField property inside the contact is used
to choose a specific field from dataProvider to display as a label of a
control. In the above example, the ComboBox control is using name as
its labelField. Note that the dataProvider contactDtails array
contains objects which have a property called name. Thus, ComboBox will
be filled in with all the name property values for all objects in the array.
Note that I did not add any event listeners or handlers in order to create automatic
data update functionality. Flex creates broadcaster/listener methods automatically
and listens for the changes in the bound value, and immediately reflects it
everywhere that the value is bound.
[ 54 ]

Chapter 2
In the previous example, you will notice a couple of new things, such as the
[Bindable] metadata tag. This tag tells the Flex compiler that this variable will be
used for data binding so that the compiler can add broadcaster and listener methods
to detect a value change.
You can use the tag as an alternative to the curly braces syntax. When
you use the tag, you provide a source property in the
tag's source property, and a destination property in its destination property.
The following example uses the tag to define data binding from a
TextInput control to a Label control:
In contrast to the curly braces syntax, you can use the tag to
completely separate the view (user interface) from the model. And it also lets you
bind multiple source properties to the same destination property because you can
specify multiple tags with the same destination.
Using the [Bindable] metadata tag
By using the [bindable] metadata tag, you instruct the Flex compiler to add
code in your application or component to detect any changes in the source
property. If change is detected, Flex copies the source property value into the
destination property. The [Bindable] tag is used to signal Flex to perform this
copy action. When [Bindable] is used, the Flex compiler automatically generates
PropertyChangeEvent and PropertyWatcher code to detect any changes.
You can use the [Bindable] metadata tag in the following different ways:
[Bindable]
[Bindable(event="event_name")]
The only difference between both syntaxes is that if you do not specify an event
name, then Flex automatically creates propertyChangeEvent for you.
[ 55 ]

Introduction to Flex 3 Framework
You can use the [Bindable] metadata tag inside MXML to make all public
variables the source of data binding by including the [Bindable] metadata tag
in the block. This is shown in the following code snippets:
[Bindable]
Or
[Bindable(event="event_name")]
You can also use the [Bindable] metadata tag inside the block of
MXML to make individual properties the source of data-binding expression, as
shown in the following code snippet:
[Bindable]
public var fooProperty:String = "fooValue";
However, by default, you can use any property as a source of data-binding
expression. Flex performs data binding when the application starts, but it will not
be able to detect any change in that property until it is defined as bindable using
metadata tag. You cannot declare constant properties as bindable for the very
obvious reason that they are constants and cannot be changed.
When you declare any object or property as bindable, Flex not only monitors it for
changes but its children properties as well. For example, you may have a bindable
object that contains another two properties. So you can use the source object's child
as the source of the data-binding expression, as shown in the following snippet:
Or
This is known as bindable property chains and you can have fairly long
property chains.
[ 56 ]