back

Create custom components for
your Flex application

by Tom Ortega II

Many of you already use Adobe Flex to build rich Internet applications. For the uninitiated, you may be wondering what makes building Flex applications so easy. It's no mystery. For starters, the Flex framework is essentially a library of prebuilt components — including containers, buttons, combo boxes, and text fields. With Flex Builder, you can build your application by simply dragging and dropping these components into your application.

But while your choice of components is vast, eventually you'll find yourself with a need that hasn't been fulfilled. What then? Since Flex is open source, you can view the source code to see how the components are constructed and then modify or build new components to suit your need.

In this article, I show you three ways to create custom components for your Flex applications. Each one is a bit more complicated than the last. However, the nice thing with Flex is that you can create components that are as simple or as complex as you like. Just find a method that works for you and use it until it just doesn't work anymore, and then increase the complexity. The three styles I cover are as follows:

You'll notice that I put the particular coding style in parentheses. One thing to remember is that these are the coding styles that the components are created in. However, this does not mean that you can only use them in the same style. As you'll see, you can use the components in your applications either as MXML tags or ActionScript classes, regardless of how they were coded because all MXML files get converted to ActionScript files by the Flex compiler. MXML just makes the user's life easier.

New project setup

Before you begin creating custom components, you need a Flex project to house them in. A Flex project is a way to tell Flex Builder that a certain set of component classes (that is, files) are tied to a particular application:

  1. Choose File > New > Flex Project.
  2. Set the Project name to EdgeArticle and click Next.
  3. Keep the default Output Folder value as bin-debug and click Next.
  4. Set the main application file to Main.mxml and click Finish.

You now have a new project entitled EdgeArticle with a single file named Main.mxml in the src folder. The Main.mxml file should be open on the screen with nothing more than an opening and closing mx:Application tag. The "mx:" is just a namespace for built-in Flex Framework classes. Later, Flex Builder will create a local: namespace for you to use. Moving forward though, I will drop the namespaces when referring to a component; therefore, the mx:Application tag will be referred to as just the Application tag.

Before moving on, you need to change one value. In the opening Application tag, set the layout attribute to vertical instead of the default, which is absolute. There are many reasons for this change, but for your purposes, this will cause your application to center your components and line them up vertically with some layout padding.

Compound components

Now it's time to create your first custom component, which is a compound type built in MXML. You will then nest other MXML tags inside of the root tag to create the component. These MXML tags are predefined components that you combine to make a new component.

Choose File > New > MXML Component. Make sure all the values match those in Figure 1.

Creating an MXML component

Figure 1. Creating an MXML component.

Now, you need to add some code to create the login screen. In the LoginScreen.mxml file, add the following code between the TitleWindow tags:

<mx:Form>
   <mx:FormItem label="Username:">
      <mx:TextInput/>
   </mx:FormItem>
   <mx:FormItem label="Password:">
      <mx:TextInput/>
   </mx:FormItem>
</mx:Form>
<mx:HBox>
   <mx:Button label="Cancel"/>
   <mx:Button label="Submit My Credentials"/>
</mx:HBox>

This code can be added manually in Code view or by dragging and dropping in Design view. Regardless of which method you use, your code should look like Figure 2.

The LoginScreen.mxml file

Figure 2. The LoginScreen.mxml file.

Now you have a form with two FormItems: one is a TextInput for username, and the other is a TextInput for password. In addition, you have an HBox with three buttons. The HBox is just a way to easily lay out items horizontally. Note that the buttons are not inside the form. Unlike HTML, the Form tag in Flex is just a layout mechanism instead of some sort of logical container.

To view the new compound component, you need to add it to your Main.mxml file. Place your cursor on line 3 in Main.mxml, which is the blank line between the two Application tags. A nice feature of Flex Builder is auto complete. If you type <Login, your screen should look like Figure 3.

The Flex Builder auto-complete feature

Figure 3. The Flex Builder auto-complete feature.

Choose the value local:LoginScreen. Flex Builder then automatically adds a new namespace for local in your opening Application tag. Namespaces are simply a way for people to use the same name, such as LoginScreen, without stepping on each other's toes. Flex uses that namespace to determine which version of a component to use. Your final Main.mxml should look like Figure 4. Note the new LoginScreen tag and the local namespace in the Application tag.

The Main.mxml file

Figure 4. The Main.mxml file.

Now that your application is ready to go, it's time to see the working application. To do this, you need to run the application. Choose Run > Run Main.

Flex Builder now takes your code and compiles it into a SWF file that runs in a browser. Once it's finished compiling, it opens up the file in your default browser. Your finished application should look like Figure 5.

The new LoginScreen compound component running inside the application.

Figure 5. The new LoginScreen compound component running inside the application.

Now you have created your first compound component in Flex.

Template components

In object-oriented programming (OOP), you have a base object. New objects then inherent from the base object or extend it. For example, let's say that Shape is your base object. You could have two shapes, Polygon and Ellipse, which extend your base Shape. Circle could then extend Ellipse. The concept here is that you start broad and specialize as you extend further and further down.

In Flex, the objects you use most are classes. The Object class is the base class of the ActionScript 3.0 OOP model. You create classes by creating MXML or ActionScript files. In the LoginScreen.mxml example, you created an MXML class, which extended the TitleWindow class.

What I refer to as a template component is one that you extend with a purpose. Let's look back at the LoginScreen. It has two buttons, but they're not the same size. You could manually size them by setting the width on each button. However, to make all the buttons in your application the same size, you need to extend the Button class to create your own SizedButton so all the buttons share the same height and size.

Choose New > ActionScript Class. Make sure all values match those in Figure 6.

Creating an ActionScript component

Figure 6. Creating an ActionScript component.

The code that you're going to add is pretty trivial. In the class constructor, add a few lines of code. The constructor is the function that has the same name as the class. Each time you create a new instance (that is, a copy) of the class, it will be called. Therefore, any code you add here will also be called for every new instance. In line 9 where it says super();, add the following code:

this.width = 180;
this.height = 30;
this.setStyle("fillColors",[0xFFFFFF,0xFFEFDF]);

This code is fairly self-explanatory. The word this is a way of designating that you're referring to the properties of the class (meaning SizedButton). You can see that the default width is set to 180 pixels, the default height is set to 30 pixels, and a new default gradient is set for the button fill colors. Your code should look like Figure 7.

The SizedButton.as file

Figure 7. The SizedButton.as file.

To see the fruits of your labor, you need to use the new component in your application. Therefore, go back to the LoginScreen.mxml file. In this file, swap out the mx:Button tags for local:SizedButton tags. While you're there, go ahead and give your TitleWindow a label as well. To do that, just add a title attribute to the TitleWindow tag. This is the same as setting the width and height properties above, but it's in MXML instead of ActionScript.

Your modified LoginScreen.mxml should look Figure 8. Note the changes on lines 2, 12, and 13.

The LoginScreen.mxml file with the SizedButton tag

Figure 8. The LoginScreen.mxml file with the SizedButton tag.

Now when you run your application, you'll see that your buttons are the same size no matter what the label is, plus they have a new color scheme. Your TitleWindow is also now living up to its namesake by displaying the title value. Note the new look of the buttons and the new title of the window.

Homegrown components

Homegrown components refer to components that you build that aren't really based on anything. These are components you create from scratch for a very specific purpose. To create this kind of component, you extend the UIComponent class, which is the class that most of the Flex visual components extend.

To fully understand what goes into creating these advanced components, I highly recommend you learn more about the Flex component lifecycle. The Advanced Visual Components in ActionScript Guide is a great resource to learn all the many facets of this process. For the advanced component, I'll show you how to use two of the methods of the lifecycle: createChildren and updateDisplayList.

To get started, create a new ActionScript class by choosing New > ActionScript Class. Match the values in Figure 9.

The FadingRectangle ActionScript class

Figure 9. The FadingRectangle ActionScript class.

This time, you will extend UIComponent. You want the FadingRectangle component to create a rectangle that has a gradient fill. When users move their mouse across this component, its alpha transparency values will change randomly based on the mouse location. It's not a very practical component, which is why it is not part of the Flex framework. However, this just demonstrates the power of Flex and how it can not only accommodate obvious business needs, but also give you the raw power to handle almost anything.

Here is the code for the class:

package
{
   import flash.display.GradientType;
   import flash.events.MouseEvent;
   
   import mx.core.UIComponent;

   public class FadingRectangle extends UIComponent
   {
      public var value:Number = 9;
      
      public var sprite:UIComponent;
      
      public function FadingRectangle()
      {
         super();
      }
      
      override protected function createChildren():void
      {
         super.createChildren();
         
         sprite = new UIComponent();
         
         addChild(sprite);
         
         sprite.addEventListener(MouseEvent.MOUSE_MOVE,changeValue);
      }
      
      override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
      {
         super.updateDisplayList(unscaledWidth,unscaledHeight);
         sprite.graphics.clear();
         sprite.graphics.beginGradientFill( GradientType.LINEAR,
            [0x0067AC, 0x002E56],
            [value % 10 * 0.1, value % 10 * 0.1],
            [0,255],horizontalGradientMatrix(0,0,300,50));
         sprite.graphics.drawRoundRect(0,0,300,50,3);
         sprite.graphics.endFill();
      }
      
      public function changeValue(event:MouseEvent):void
      {
         value = event.localX + event.localY;
         invalidateDisplayList();
      }
      
   }
}

You should be able to copy and paste this code to completely overwrite the file contents of the FadingRectangle.as class.

Let's take a closer look at the code. First, we created two properties (also called class variables):

public var value:Number = 9;
public var sprite:UIComponent;

The value property is used to calculate the alpha level of the rectangle. The sprite property is a UIComponent where we draw the rectangle.

Next, we override the createChildren function so we can add our own children to the component. The child we want to add is the sprite where we will be doing all of our drawing:

override protected function createChildren():void

Additionally, we set up an event listener on the sprite. Specifically, we say that if the mouse rolls over the rectangle, call the changeValue function:

public function changeValue(event:MouseEvent):void

Inside this function, we set the value for later use. We then call invalidateDisplayList(). This just tells the Flex framework that we need to redraw the component again:

override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void

We override this function so we can draw (and redraw) our rectangle. Each time, we adjust the alpha levels based on the last mouse location.

The last thing you need to do is add it to your LoginScreen component. Add it under the buttons so that your LoginScreen code now looks like Figure 10. You can see your new component on line 15.

The LoginScreen component with the fading rectangle

Figure 10. The LoginScreen component with the fading rectangle.

Run the application again. Move your mouse around under the buttons. You should see the rectangle fading in and out based on your mouse movement. If you haven't been building all along but you want to see the finished application, check out Figure 11 (it's interactive).

AlertThis content requires Flash

To view this content, JavaScript must be enabled, and you need the latest version of Adobe® Flash® Player.

Download the free Flash Player now!

Get Adobe Flash Player

Figure 11. The completed application with all three custom components.

Where to go from here

As you can see, building custom components inside Flex can be accomplished in more than one way. You can create a new component by putting lots of other components together. You can create customized versions of existing components by merely extending them with some default properties. You can even break away from the normal class types but still leverage and harness the full potential of the Flex Framework.

The attraction of Flex lies in its underlying component makeup. The ability for developers to compose, extend, or create components is powerful. It enables quick yet robust development of today's demanding rich Internet applications. If you need a component, chances are someone has already built it. If not, you can share yours once you create it.

If you want to learn more about custom components, there are plenty of resources. Flex.org and the Flex Developer Center are great places to start. Adobe's online resources for Flex 3 are also helpful. Lastly, if you want to experience the Flex community, attend the next 360|Flex conference or find your local user group.

 

Participate in a survey about developer tools and services… and be entered to win a 32 GB Apple® iPod Touch

 

‹ Back


Tom Ortega II is a Principal at 360Conferences, where he coordinates low-cost, developer-friendly conferences such as 360Flex and 360|iDev. In addition, he keeps up his coding skills with projects at RapidNinja under the alias of "Ninja Debu".