Learning Flex Basics (Part 1): Creating Your First Flex Application
Robert Crooks
In this tutorial you will learn the basic elements of Macromedia Flex applications through an overview and through building a simplified catalog and shopping cart in MXML. To do this you will create an application, add a layout container, add controls, create a simple data model that is bound to controls, and finally create event-handler functions in ActionScript.
If you like what you see and want to get more experience with Flex,
Macromedia Customer Training offers Developing Rich Internet Applications with Macromedia Flex, a two-day onsite training course to jump-start Flex development in your organization. Now let's get started!
If you are new to writing XML languages, remember these basic rules:
- Both tag and attribute names in MXML, as in all XML languages is case-sensitive
- All values for attributes must be in single or double quotation marks
- All tags must be closed. Tags that contain no nested tags or content can be closed with a simple slash rather than a full end tag:
<mx:Label text="Hello"></mx:Label>
or
<mx:Label text="Hello"/>
If you are new to ActionScript, you will probably find the syntax similar to languages you already know, such as JavaScript or Java. Remember these basic rules:
- ActionScript is case-sensitive
- Statements are terminated by a semi-colon (;)
What You Will Learn:
- Get a brief overview of Flex
- How to use the Application tag.
- How to use a Panel container.
- How to use a Label control.
- How to use a Text control.
- How to use Button controls.
- How to use a ComboBox control.
- How to create an array of objects.
- How to bind data to controls.
- How to create an ActionScript handler for a user event.
Requirements
To complete this tutorial you will need to install the following software and files:
Macromedia Flex
A Text Editor
Flex Builder, Dreamweaver MX 2004, or a text editor that you can use to write XML and ActionScript code (a basic text editor such as Notepad is adequate). You can download Flex Builder with the Flex server try/buy links above. Use the following links to try/buy Dreamweaver MX 2004:
Solution files for this tutorial:
Prerequisite knowledge:
A Brief Overview of Macromedia Flex
Macromedia Flex is a server component that enables you to create rich presentation layers for Internet applications. Interfaces built in Flex rely on Macromedia Flash Player for display on client systems. The essential components of Flex are:
- An XML language (MXML) used to describe the application interface.
- An ECMA scripting language (ActionScript) used with MXML to handle user and system events or to construct complex data models.
- A class library
- Runtime services
- A compiler that generates SWF files from MXML files.
MXML
MXML is an XML 1.0 language used to describe Flex presentation layers. Every MXML file should begin with an XML declaration:
<?xml version="1.0"?>
Like other XML languages, MXML includes elements (coded as tags) and attributes whose names are case-sensitive. Element names begin with a capital letter and use mixed case, and you must close all elements:
<ComboBox></ComboBox>
You may also close elements that have no contents with an ending /:
<ComboBox/>
Attributes begin with lowercase and use mixed case. You must enclose all values for attributes in quotation marks.
<ComboBox id="myCombo"/>
For all attributes except events like click or initialize, attribute values are assumed to be literal strings by the compiler. To bind data and force the compiler to evaluate an expression, you can wrap all or part of the value in curly braces:
<ComboBox dataProvider="{myArray}"/>
You can write most attributes as subtags with values written as contents:
<ComboBox dataProvider="{myArray}"/>
Or:
<ComboBox> <dataProvider>{myArray}</dataProvider> </ComboBox>
MXML files that describe full applications will have an Application element that encloses all other elements:
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml">
[other elements...]
</mx:Application>
Note the xmlns
attribute, which declares an XML namespace. Namespaces let you use multiple XML languages in a single document without confusion between identical element names that are used differently in different languages. The :mx
here defines a prefix used for a particular namespace.
Note: The namespace declaration here is a standard one for the MXML class library; include it in every MXML file.
Place the declaration in any MXML tag; doing this makes it available to all elements nested inside that tag. Using the mx
prefix for the MXML class library is a recommended practice that this tutorial series will follow throughout these tutorials.
ActionScript
ActionScript is an object-oriented scripting language similar to JavaScript and other ECMA scripting languages. If you have used JavaScript or object-oriented programming languages like Java or C#, you will find most of ActionScript syntax familiar. You can embed ActionScript code directly in MXML or import it from separate files.
The MXML Class Library
Flex includes an extensive class library for both visual components such as controls and containers, and faceless components such as remote service objects and data models. You will look at many of these in some detail in the tutorials.
Runtime Services
Flex provides several runtime services such as history management and access of remote service objects. From a development perspective, these services are invoked transparently through the class library.
Compiler
The Flex compiler automatically compiles the corresponding SWF when the browser requests an MXML file. The SWF file is automatically cached until you modify the source files.
Running Flex Applications
You can run your Flex applications in a web browser. The exact URL will depend on how and where you installed Flex. If you install the integrated Macromedia JRun server, the general URL for your Flex applications will be:
http://localhost:8700/flex/
The exact URL for the application you build in the first of these tutorials, then, would be:
http://localhost:8700/flex/flex_tutorials/firstapp.mxml
The number, 8700, is the port that Flex runs on. If you install Flex to run on a full version of JRun or some other J2EE application server, you will need to substitute the appropriate port number.
Building the Application
In this simplified cart, you will display a list of coffee blends in a ComboBox (similar to an HTML select control). You will use data binding to display a description of the currently selected blend, and a Button with a click handler to add a blend to a List control that represents the shopping cart.
Figure 1. The Flex application you'll build in this tutorial.
In building the cart you will learn to use:
- The Application class
- The Panel container
- The Script element
- The Array element
- The Object element
- The Label element
- The Text element
- The Button control
- The ComboBox control
- The List control
- An ActionScript function
Create the Application Object
To begin any Flex application, start with an XML declaration and an Application
block. The Application
tag will include a namespace declaration for the MX class library: xmlns:mx="http://www.macromedia.com/2003/mxml"
. The mx
prefix is used with all tags for this library.
- Create a new file and save it as firstapp.mxml in the flex_tutorials directory.
- At the beginning of the file, insert the XML declaration:
-
After the XML declaration, add an Application
tag with the MXML namespace:
<mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml">
</mx:Application>
Add a Panel for the Application Layout
You generally place the visual components of your Flex application inside containers, which provide bounding boxes for text, controls, images, and other media elements. Here, you will use a container called Panel, which will provide the overall visual wrapper for most applications. You will also use the title attribute of Panel, which provides title text that will display in a title bar that is automatically included at the top of the panel.
-
Inside the Application block, add a Panel block with the title attribute equal to "My First Flex App":
<mx:Panel title="My First Flex App">
</mx:Panel>
Add a Label for the View Header
Use the Label element to display a single line of text. It has a number of properties; here you use the text attribute, which defines the text that will display in the Label
-
Inside the Panel block, add a Label with the attributes as shown below:
<mx:Label text="Coffee Blends"/>
- Save the file and browse the application.
Add an Array of Objects to Define the Coffee Blends
The data model for this application is an array of objects that you build directly into the application using the Array and Object elements. Each of the objects has two properties, label and data, which you define as subtags in the Objects. This data structure corresponds to the dataProvider form used by controls like the ComboBox and List, which you use later in this tutorial.
These controls can use more complex data objects, but since you build the data model manually here, you use the simple form. The general syntax you use is:
<mx:Array id="identifier">
<mx:Object>
<label>literal string</label>
<data>another literal string</data>
</mx:Object>
</mx:Array>
The id
attribute is available for nearly all Flex classes, and you use it to provide a unique identifier for an instance of the class. You need not provide an explicit id
value unless you plan to refer to the object in data bindings or ActionScript.
Placement of faceless elements such an array is up to you, but it is good practice to place them the top of the application, above visual elements.
- Inside the Application block, before the Panel, add the following array of objects:
<mx:Array id="coffeeArray">
<mx:Object>
<label>Red Sea</label>
<data>Smooth and fragrant</data>
</mx:Object>
<mx:Object>
<label>Andes</label>
<data>Rich and pungent</data>
</mx:Object>
<mx:Object>
<label>Blue Mountain</label>
<data>Delicate and refined</data>
</mx:Object>
</mx:Array>
Add a ComboBox to Display the Coffee Blends
The Flex ComboBox is similar to an HTML select control, though more robust. The dataProvider property sets the items to display in an array of simple values or objects. You can create the array directly within a dataProvider block, but a more common approach is to create or import the data elsewhere and bind it to the dataProvider property:
<mx:ComboBox id="myCombo" dataProvider="{myArray}"/>
The curly braces signal the compiler that what's inside is an expression or variable to evaluate rather than a literal string.
If the objects contain label
and data
properties, these are used automatically for the displayed items and data associated with them—the data can be a scalar value or complex type such as an object. If the objects do not have label and data properties, then the entire objects are used for the item data properties, and the label value is set to one of the object properties using the labelField
property of the ComboBox.
-
Add a ComboBox control after the Label, giving an id
of coffeeCombo
and using the dataProvider
property to bind the ComboBox to the coffeeArray you created in the previous step:
<mx:ComboBox id="coffeeCombo" dataProvider="{coffeeArray}"/>
Add a Text Control to Display the Description
A Text control is similar to a Label, except that it can display multiline data. Here you use it to display the description of the selected coffee blend by binding it to the data associated with the item that the user selected in the ComboBox. The data object is referenced as the selectedItem
property of the ComboBox.
-
After the ComboBox, add a Text control with the text
property, set to the literal string Description:, and add a binding to the data property of the selected item in the ComboBox:
<mx:Text text="Description: {coffeeCombo.selectedItem.data}"/>
Add a Button to Add a Coffee Blend to the Shopping Cart
The Button control is straightforward. It has a label
property for the text label to display. It also has a click
event set equal to an ActionScript expression or event-handler that will execute when the user clicks the button.
In this case, you add a Button that adds the selected item in the ComboBox to a simple cart by using the click event to call a function called addToCart()
. You create this function and the cart in later steps.
-
After the Text control, add a Button with a label that says "Add to Cart" and click event that calls an addToCart()
function:
<mx:Button label="Add to Cart" click="addToCart()"/>
Add a List Control for the Shopping Cart
The List control is identical to the ComboBox, except that it displays and lets the user select multiple items at once. The List here will have no dataProvider, because it will be empty until the user adds items to it.
-
After the Button, add a List control with an id
of cart:
Add a Script to Handle the Button Click Event
The final step of the tutorial is to add an ActionScript function to handle the click event on the Button. For this simple application, add the function in a Script block.
The ActionScript code inside the Script block will be wrapped in a <![CDATA[ ]]>
wrapper, which instructs the XML parser to pass the contents of the wrapper through without parsing them. This technique is standard XML practice, used here in case the script contains any characters (such as a <
symbol) that the parser might misinterpret as XML code. As it happens, the code here will contain no such reserved characters, but it's good to get in the habit of wrapping embedded script code in CDATA just in case—it does no harm, and also saves the parser the trouble of parsing non-XML code.
The ActionScript here is quite simple. The general syntax for functions is:
function functionName(parameter1:dataType...):returnDataType
{
[ActionScript statements]
}
In the addToCart()
function, use the addItem()
method of the List class, which takes the parameters label
and data
. The arguments you pass are simply the label and data properties of the selected item in the ComboBox.
-
After the Array block, insert a Script block with a CDATA
wrapper nested inside:
<mx:Script>
<![CDATA[]]>
</mx:Script>
-
Inside the CDATA wrapper, add an ActionScript function called addToCart()
that returns nothing;:
function addToCart():Void
{
}
-
Inside the function block, use the addItem method for the cart List to add the label and data properties of the selected item in the ComboBox:
cart.addItem(coffeeCombo.selectedItem.label,coffeeCombo.selectedItem.data);
- Save the file and test it in a web browser (for information on how to browse MXML files, see the first page in this tutorial).
Complete Code Listing for firstapp.mxml
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml" >
<!-- data model -->
<mx:Array id="coffeeArray">
<mx:Object>
<label>Red Sea</label>
<data>Smooth and fragrant</data>
</mx:Object>
<mx:Object>
<label>Andes</label>
<data>Rich and pungent</data>
</mx:Object>
<mx:Object>
<label>Blue Mountain</label>
<data>Delicate and refined</data>
</mx:Object>
</mx:Array>
<mx:Script>
<![CDATA[
function addToCart():Void
{
cart.addItem(coffeeCombo.selectedItem.label,coffeeCombo.selectedItem.data);
}
]]>
</mx:Script>
<!-- view -->
<mx:Panel title="My First Flex App">
<mx:Label text="Coffee Blends"/>
<mx:ComboBox id="coffeeCombo" dataProvider="{coffeeArray}"/>
<mx:Text text="Description: {coffeeCombo.selectedItem.data}"/>
<mx:Button label="Add to Cart" click="addToCart()"/>
<mx:List id="cart"/>
</mx:Panel>
</mx:Application>
Where to Go from Here
In this simple application, you have learned about several core building blocks for Flex applications: containers, controls, data models, data-binding, and event handlers. Continue on to the following tutorials to learn more:
If you like what you see and want to get more experience with Flex,
Macromedia Customer Training offers Fast Track to Macromedia Flex, a two-day onsite training course to jump-start Flex development in your organization. You should also look at the informative set of sample applications in included with Flex; these illustrate the use of many Flex features. You can also read the next tutorial online at: Building a Simple Calculator with Macromedia Flex.
About the author
Robert Crooks is the Director of Curriculum Development for Macromedia. He has written several courses on creating internet applications including the beta version of Fast Track to Macromedia Flex.