Flex 101 with Flash Builder 4: Part 1

Exclusive offer: get 50% off this eBook here
Flex 3 with Java

Flex 3 with Java — Save 50%

Develop rich internet applications quickly and easily using Adobe Flex 3, ActionScript 3.0 and integrate with a Java backend using BlazeDS 3.2

$23.99    $12.00
by Romin Irani | July 2009 | Java Open Source

Rich Internet Applications (RIA) have garnered a lot of attention in recent times and rightly so. They offer a rich and responsive user interface and embed several Web 2.0 features that are required in today’s applications. Key features among them include rich media integration, responsiveness, real-time, offline capabilities and a desktop/web deployment model.

There are several tools/frameworks available today to develop RIAs. One of the leading frameworks that has garnered a lot of attention and developer interest over the last couple of years is the Flex Framework from Adobe Systems.

This article by Romin Irani introduces the RIA development framework Flex and its development IDE Flash Builder 4 (FB4) to the readers. The article covers the following:

  • What is Flex Ecosystem
  • Setting up the Development IDE, Flash Builder Beta 4
  • Sample programs that take the reader through the mechanics of developing applications using Flash Builder 4.

 

The article is intended towards developers who have never used Flex before and would like to exercise a “Hello World” kind of tutorial. The article does not aim to cover Flex and FB4 in detail but rather focuses on the mechanics of FB4 and getting an application running with minimal effort.

For developers familiar with Flex and the predecessor to Flash Builder 4 (Flex Builder 2 or 3), it contains an introduction to FB4 and some differences in the way you go about building Flex Applications using FB4.

Even if you have not programmed before and are looking at understanding how to make a start in developing applications, this would serve as a good start.

The Flex Ecosystem

The Flex ecosystem is a set of libraries, tools, languages and a deployment runtime that provides an end-to-end framework for designing, developing and deploying RIAs. All these together are being branded as a part of the Flash platform.

In its latest release, Flex 4, special efforts have been put in to address the designer to developer workflow by letting graphic designers address layout, skinning, effects and general look and feel of your application and then the developers taking over to address the application logic, events, etc.

To understand this at a high level, take a look at the diagram shown below. This is a very simplified diagram and the intention is to project a 10,000 ft view of the development, compilation and execution process.

Flex 101 with Flash Builder 4: Part 1

Let us understand the diagram now:

  1. The developer will typically work in the Flash Builder Application. Flash Builder is the Integrated Development Environment (IDE) that provides an environment for coding, compiling, running / debugging your Flex based applications.
  2. Your Flex Application will typically consist of MXML and ActionScript code. ActionScript is an ECMAScript compatible Object Oriented language, whereas MXML is an XML-based markup language.
  3. Using MXML you can define/layout your visual components like buttons, combobox, data grids, and others. Your application logic will be typically coded inside ActionScript classes/methods.
  4. While coding your Flex Application, you will make use of the Flex framework classes that provide most of the core functionality. Additional libraries like Flex Charting libraries and 3rd party components can be used in your application too.
  5. Flash Builder compiles all of this into object byte code that can be executed inside the Flash Player. Flash Player is the runtime host that executes your application.

This is high level introduction to the ecosystem and as we work through the samples later on in the article, things will start falling into place.

Flash Builder 4

Flash Builder is the new name for the development IDE previously known as Flex Builder. The latest release is 4 and it is currently in public beta.

Flash Builder 4 is based on the Eclipse IDE, so if you are familiar with Eclipse based tools, you will be able to navigate your way quite easily. Flash Builder 4 like Flex Builder 3 previously is a commercial product and you need to purchase a development license. FB4 currently is in public beta and is available as a 30-day evaluation.

Through the rest of the article, we will make use of FB4 and will be focused completely on that to build and run the sample applications. Let us now take a look at setting up FB4.

Setting up your Development Environment

To setup Flash Builder 4, follows these steps:

  1. The first step should be installing Flash Player 10 on your system. We will be developing with the Flex 4 SDK that comes along with Flash Builder 4 and it requires Flash Player 10. You can download the latest version of Flash Player from here: http://www.adobe.com/products/flashplayer/
  2. Download Flash Builder 4 Public Beta from http://labs.adobe.com/technologies/flashbuilder4/. The page is shown below:

Flex 101 with Flash Builder 4: Part 1

After you download, run the installer program and proceed with the rest of the installation.

Launch the Adobe Flash Builder Beta. It will prompt first with a message that it is a Trial version as shown below:

Flex 101 with Flash Builder 4: Part 1

To continue in evaluation mode, select the option highlighted above and click Next. This will launch the Flash Builder IDE.

Let us start coding with Flash Builder 4 IDE. We will stick to tradition and write the “Hello World” application.

Hello World using Flash Builder 4

In this section, we will be developing a basic Hello World application. While the application does not do much, it will help you get comfortable with the Flash Builder IDE.

Launch the Flash Builder IDE. We will be creating a Flex Project. Flash Builder will help us create the Project that will contain all our files. To create a new Flex Project, click on the File → New → Flex Project as shown below:

Flex 101 with Flash Builder 4: Part 1

This will bring up a dialog in which you will need to specify more details about the Flex Project that you plan to develop. The dialog is shown below:

Flex 101 with Flash Builder 4: Part 1

You will need to provide at least the following information:

  • Project Name: This is the name of your project. Enter a name that you want over here. In our case, we have named our project MyFirstFB4App.
  • Application Type: We can develop both a Web version and a desktop version of our application using Flash Builder. The web application will then run inside of a web browser and execute within the Flash Player plug-in. We will go with the Web option over here. The Desktop application runs inside the Adobe Integrated Runtime environment and can have more desktop like features. We will skip that option for now.
  • We will let the other options remain as is. We will use the Flex 4.0 SDK and currently we are not integrating with any Server side layer so we will leave that option as None/Other.

Click on Finish at this point to create your Flex Project. This will create a main application file called MyFirstFB4App.mxml as shown below.

Flex 101 with Flash Builder 4: Part 1

We will come back to our coding a little later but first we must familiarize ourselves with the Flash Builder IDE.

Let us first look at the Package Explorer to understand the files that have been created for the Flex Project. The screenshot is shown below:

Flex 101 with Flash Builder 4: Part 1

It consists of the main source file MyFirstFB4App.mxml. This is the main application file or in other words the bootstrap. All your source files (MXML and ActionScript code along with assets like images, and others should go under the src folder. They can optionally be placed in packages too.

The Flex 4.0 framework consists of several libraries that you compile your code against. You would end up using its framework code, components (visual and non-visual) and other classes. These classes are packaged in a library file with an extension .swc. A list of library files is shown above. You do not need to typically do anything with it.

Optionally, you can also use 3rd party components written by other companies and developers that are not part of the Flex framework. These libraries are packages as .SWC files too and they can be placed in the libs folder as shown in the previous screenshot.

The typical step is to write and compile your code—build your project. If your build is successful, the object code is generated in the bin-debug folder. When you deploy your application to a Web Server, you will need to pickup the contents from this folder. We will come to that a little later. The html-template folder contains some boiler-plate code that contains the container HTML into which your object code will be referenced. It is possible to customize this but for now, we will not discuss that.

Double-click MyFirstFB4App.mxml file. This is our main application file. The code listing is given below:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/halo"
minWidth="1024" minHeight="768">

</s:Application>

As discussed before, you will typically write one or more MXML files that will contain typically your visual components (although there can be non-visual components also). By visual components, we mean controls like button, combobox, list, tree, and others. It could also contain layout components and containers that help you layout your design as per the application screen design.

To view what components, you can place on the main application canvas, select the Design View as shown below:

Flex 101 with Flash Builder 4: Part 1

Have a look at the lower half of the left pane. You will see the Components tab as shown below, which would address most needs of your Application Visual design.

Flex 101 with Flash Builder 4: Part 1

Click on the Controls tree node as shown below. You will see several controls that you can use and from which, we will use the Button control for this application.

Flex 101 with Flash Builder 4: Part 1

Simply select the Button control and drag it to the Design View Canvas as shown below:

Flex 101 with Flash Builder 4: Part 1

This will drop an instance of the Button control on the Design View as shown below:

Flex 101 with Flash Builder 4: Part 1

Select the Button to see its properties panel as shown below. Properties Panel is where you can set several attributes at design time for the control. In case the Properties panel is not visible, you can get to that by selecting Window → Properties from the main menu.

Flex 101 with Flash Builder 4: Part 1

In the Properties panel, we can change several key attributes. All controls can be uniquely identified and addressed in your code via the ID attribute. This is a unique name that you need to provide. Go ahead and give it some meaningful name. In our case, we name it btnSayHello.

Next we can change the label so that instead of Button, it can display a message for example, Say Hello. Finally we want to wire some code such that if the button is clicked, we can do some action like display a Message Box saying Hello World.

To do that, click the icon next to the On click edit field as shown below. It will provide you two options. Select the option for Generate Event Handler.

Flex 101 with Flash Builder 4: Part 1

This will generate the code and switch to the Source view. The code is listed below for your reference.

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/halo"
minWidth="1024" minHeight="768">

<fx:Script>
<![CDATA[
protected function btnSayHello_clickHandler(event:MouseEvent):void
{
// TODO Auto-generated method stub
}
]]>
</fx:Script>

<s:Button x="17" y="14" label="Button" id="btnSayHello"
click="btnSayHello_clickHandler(event)"/>

</s:Application>

There are few things to note here. As mentioned most of your application logic will be written in ActionScript and that is exactly what Flash Builder has generated for you. All such code is typically added inside a scripting block marked with the <fx:Script> tag. You can place your ActionScript methods over here that can be used by the rest of the application.

When we clicked on Generate Event Handler, Flash Builder generated the Event Handler code. This code is in ActionScript and was appropriately placed inside the <fx:Script> block for us.

If you look at the code, you can see that it has added a function that is invoked when the click event is fired on the button.

The method is btnSayHello_clickHandler and if you notice it has an empty method that is, no implementation.

Let us run the application now to see what it looks like. To run the application, click on the Flex 3 with Java  Run icon in the main toolbar of Flash Builder.

This will launch the web application as shown below. Clicking the Say Hello button will not do anything at this point since there is no code written inside the handler as we saw above.

Flex 101 with Flash Builder 4: Part 1

To display the MessageBox, we add the code shown below (Only the Script section is shown below):

<fx:Script>
<![CDATA[
import mx.controls.Alert;

protected function btnSayHello_clickHandler(event:MouseEvent):void
{
Alert.show("Hello World");
}
]]>
</fx:Script>

We use one of the classes (called Alert) from the Flex framework. Like any other language, we need to specify which package we are using the class from so that the compiler can understand it. The Alert class belongs to the mx.controls package and it has a static method called show() which takes a single parameter of type String. This String parameter is the message to be displayed and in our case it is "Hello World".

To run this, click Ctrl-S to save your file or File →  Save from the main menu. And click on Run icon in the main toolbar. This will launch the application and on clicking the SayHello button, you will see the Hello World Alert window as shown below. 

Flex 101 with Flash Builder 4: Part 1

Flex 3 with Java Develop rich internet applications quickly and easily using Adobe Flex 3, ActionScript 3.0 and integrate with a Java backend using BlazeDS 3.2
Published: June 2009
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Yahoo! News Application

Let us write another application, we will call it the Yahoo! News Application. This application shows a list of current news items from Yahoo that has been classified as "most emailed".

Yahoo! provides this list in the form of a RSS feed. The RSS feed for the same is: http://rss.news.yahoo.com/rss/mostemailed.

Let us first look at the application when it is all ready so that we can understand what we are trying to build. The snapshot is shown below:

Flex 101 with Flash Builder 4: Part 1

The application is simple. It has a button called Fetch News, which when clicked will connect to the internet, access the RSS Feed and display the new items. It shows the news items by using a DataGrid component that can show rows of data, which can comprise several columns. In our case, each row is one news item and we are currently displaying only one column —title of the news item.

Let us build this application now. To start off, we will create another application which we shall call YahooNews. You do not need to create another project and can stay within the MyFirstFB4App project and create a new MXML application by going to the main menu and selecting File → New → MXML Application. This will bring up a dialog window as shown below. Give the Filename as YahooNews and select the Layout as spark.layouts.VerticalLayout (This will arrange all your components vertically at the main application canvas level).

Finally, click on the Finish button.

Flex 101 with Flash Builder 4: Part 1

This will generate the same boilerplate code that we saw earlier. Go to the Design View and then from the Components tab, first drag and drop a Button from the Controls tree node. The properties of the button are shown below:

Flex 101 with Flash Builder 4: Part 1

Create a click handler for the button as shown below:

Flex 101 with Flash Builder 4: Part 1

Go back to the Design view and drop a DataGrid control from the Components tab as shown below. Note that the DataGrid component is present in the Data Controls tree node. The DataGrid component is like a table and visually it can display rows of data where each row can comprise one of more columns.

Flex 101 with Flash Builder 4: Part 1

The Design view is shown below. By default the DataGrid shows 3 sample columns and we need to restrict that to just one column in which we wish to show the title. We wish to name the column header as "News Title".

Flex 101 with Flash Builder 4: Part 1

You can modify the DataGrid properties by selecting the DataGrid control and viewing the Properties Tab. First let us set the ID to dgNews.

Flex 101 with Flash Builder 4: Part 1

Then set the width and height of this control to 100% respectively. This means that it will occupy the whole application screen even if you resize it.

Flex 101 with Flash Builder 4: Part 1

You can view the current columns and modify (add/delete/edit) them by clicking on the Configure Columns button in the Properties Tab. That will bring up the current columns as you can see below:

Flex 101 with Flash Builder 4: Part 1

We need only one column, so to delete Column 2 and Column 3, simply select the item and click on the Delete button. Additionally, select Column 1 and change the following two properties:

  1. Bind to field: This is the attribute of the row object. For example we are going to assign a list of news items that is a collection of news items to the DataGrid. Each row is a news item object and each item object consists of several attributes like title, pubDate, category, and others as per the RSS definition. So in this case we are interested in only the title attribute or property.
  2. Header Text: This is the text that is shown in the header column for the DataGrid. We will call it News Title.

Flex 101 with Flash Builder 4: Part 1

Click on OK to commit the changes.

The final step will be for us to implement the code in our handler which we auto generated when the Fetch News button is clicked. Switch over the Source view to take a look at the current code generated for you.

Let us go through the code:

  1. Take a look at the Fetch News button code shown below:
      <s:Button id="btnFetchYahooNews" label="Fetch News!"  
      click="btnFetchYahooNews_clickHandler(event)"/>
      protected function  
      btnFetchYahooNews_clickHandler(event:MouseEvent):void
      {
      // TODO Auto-generated method stub
      }
  2. This code is straightforward and it means that when the button is clicked the method btnFetchYahooNews_clickHandler will be invoked.

    Since we auto-generated the click handler, it currently looks like this:

    We need to now implement the code to do the following:

  3. To do that, we will need to use the HTTPService from the mx namespace in the Flex framework. The HTTPService is a non-visual component and hence it is defined under a <fx:Declaration> tag as given below:
      <fx:Declarations>
      <mx:HTTPService id="YahooNewsService"
      url="http://rss.news.yahoo.com/rss/mostemailed"
      method="GET"
      result="YahooNewsService_resultHandler(event)"
      fault="YahooNewsService_faultHandler(event)"/>
      </fx:Declarations>
  4. The <fx:Declarations> tag is created under the <mx:Application> main tag. We first have an id attribute that is a unique name for the service. Then the url attribute that points to the RSS Feed. We are using the GET method for the HTTP operation. Finally, two critical events are handled. One of them is the result event which is invoked when the HTTP Request has been successful and a response is returned. The other is a fault event which is invoked when the HTTP Request could not be completed and there was an error.

  5. Let us look at the complete code now where we hook up invoking of the Fetch News button to the HTTP Service and then binding the result of the HTTP Response to the DataGrid.
      <?xml version="1.0" encoding="utf-8"?>
      <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
      xmlns:s="library://ns.adobe.com/flex/spark"
      xmlns:mx="library://ns.adobe.com/flex/halo" minWidth="1024" minHeight="768">

      <fx:Declarations>
      <mx:HTTPService id="YahooNewsService" url="http://rss.news.yahoo.com/rss/mostemailed"
      method="GET"
      result="YahooNewsService_resultHandler(event)"
      fault="YahooNewsService_faultHandler(event)"/>
      </fx:Declarations>

      <fx:Script>
      <![CDATA[
      import mx.rpc.events.FaultEvent;
      import mx.rpc.events.ResultEvent;

      import mx.controls.Alert;

      //This handler is invoked when FetchNews button is clicked
      protected function btnFetchYahooNews_clickHandler(event:MouseEvent):void
      {
      //Send the HTTP Request by invoking the send() method
      YahooNewsService.send();
      }

      //When the HTTP Response is received bind the result to the DataGrid's dataprovider

      protected function YahooNewsService_resultHandler(event:ResultEvent):void
      {
      dgNews.dataProvider = event.result.rss.channel.item;
      }


      protected function YahooNewsService_faultHandler(event:FaultEvent):void
      {
      Alert.show("Error in fetching Yahoo News.");
      }

      ]]>
      </fx:Script>

      <s:layout>
      <s:VerticalLayout/>
      </s:layout>
      <s:Button id="btnFetchYahooNews" label="Fetch News!"
      click="btnFetchYahooNews_clickHandler(event)"/>
      <mx:DataGrid width="100%" height="100%" id="dgNews">
      <mx:columns>
      <mx:DataGridColumn dataField="title" headerText="News Title"/>
      </mx:columns>
      </mx:DataGrid>
      </s:Application>

Let us go through the key points:

  • The btnFetchYahooNews_clickHandler method is invoked when the Fetch News button is clicked. In this method, we send the HTTP Request by invoking the send() method on the HTTPService instance—YahooNewsService.
  • As mentioned the result event is fired when the HTTP Response is available. The HTTP response is available in the event parameter that is passed to the result handler. Since it is a standard RSS feed that is available, a collection of items is available under the event.result.rss.channel.item object.
  • This is then assigned to the Data Grid. To assign it to the DataGrid, we simply pass it to the dataProvider attribute of the grid. Since we have bound the column to only the title attribute, the DataGrid takes care of the column rendering for us.

To run the application, simply click on the Run icon in the main toolbar. A sample output is shown below:

Flex 101 with Flash Builder 4: Part 1

>> Continue Reading Flex 101 with Flash Builder 4: Part 2

 

[ 1 | 2 ]
Flex 3 with Java Develop rich internet applications quickly and easily using Adobe Flex 3, ActionScript 3.0 and integrate with a Java backend using BlazeDS 3.2
Published: June 2009
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Romin Irani is a software developer at heart, living and working in Mumbai, India. He has been developing software for 15 years now and still wakes up every morning to learn something new in the ever changing world of software development. He has been a big fan of all things related to Flex, ever since he came across it 3 years back.

He has a one-point agenda: Harness the power of software by learning, teaching and developing simple solutions. You can follow him on Twitter at http://www.twitter.com/iromin.

Books From Packt

Flash with Drupal
Flash with Drupal

Joomla! 1.5x Customization: Make Your Site Adapt to Your Needs
Joomla! 1.5x Customization: Make Your Site Adapt to Your Needs

Magento 1.3 Theme Design
Magento 1.3 Theme Design

Scratch 1.4: Beginner’s Guide
Scratch 1.4: Beginner’s Guide

WordPress MU 2.7: Beginner's Guide
WordPress MU 2.7: Beginner's Guide

LWUIT 1.1 for Java ME Developers
LWUIT 1.1 for Java ME Developers

Drupal 6 Content Administration
Drupal 6 Content Administration

Zend Framework 1.8 Web Application Development
Zend Framework 1.8 Web Application Development

No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
H
m
9
8
k
n
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software