Developing Flex Components

Maret 17, 2008 at 4:16 pm 2 komentar

Introduction
This tutorial aims to teach you in detail how to develop a Flex component using Actionscript classes. The object of the tutorial is to guide developers on the key steps necessary to generate a distributable Flex component in SWC format. The SWC format is Adobe’s packaging mechanism where assets such as classes, codes, images, swf etc are bundled together into one zipped file for easy access. In reality, you can unpack all the contents of an SWC component using a zip application like WinRar but accessing the main swf after unpacking makes it unstable to use again. So if you want to experiment, make a copy before doing that. We are developing a simple drag and drop component based on Flex’s Panel class, it therefore extends the capabilities of the Panel class. It’s called Adjustable and what it simply does is that it gives the user, the privilege of adjusting the width of a Panel from the right edge at runtime. It leaves the reader with the challenge to extend it to include height as well.

Requirements
1. Flex Builder 2.0 (You can get it here) OR Flash Develop (You can get it here)
2. Download Source Code with sample here

Tutorial
First, lets create the project in Flex Builder. Create a new project but this time, make it a Library Project. This ensures that the final output is an SWC file and not an swf. Name the project “Adjustable” and create a new folder for it anywhere you fell good about. If you are using Flash Develop, just create a new Project named “Adjustable” and select “Actionscript 2 – Flex 2 Project” from the installed Templates. Let the application create a new Folder and click Ok. Now we are ready! First create a new Folder named “Flexcubed”, you can use any name you so choose, but it’s advisable to structure your components in recognizable packages. This is the package name for the Adjustable Panel component I chose. Select the folder and Right Click to select New Actionscript Class from both applications. This will bring up a dialog for you to create a new AS class with the folder name as the package. Label this Class as Adjustable and in Flex Builder, select Panel as the base class. This is our main Class file that defines what the component will do. In it we have:

package Flexcubed {
    import mx.containers.Panel;
    public class Adjstable extends Panel{
 	public function Adjstable(){
		super();
	}
    }
}

It’s quite straightforward, the package is Flexcubed, the class is Adjustable and it extends the Panel Class as its base class. The import tells the compiler to import the Panel class from mx.containers. The function Adjustable() is the first function executed once the component runs so there we put the super() function. It simply tells the component to run the main function of the base Panel class, thats all. Please run the sample to have a feel of what we are developing. From the sample, you will observe a Black Mouse pointer that’s use in resizing when you mouse over the edge of the panel. That is not a system mouse icon so we are going to embed that as an image asset into our component. This line does it:

[Embed(source="../assets/resizeLeft.gif")]
public var leftMouse:Class;

The [Embed] is a meta information that tells the compiler where to locate the image and embed it into the swc for later use and we gave it a class name “leftMouse” so in our code, when we use that name, it refers to that asset. This could be a jpeg, png or gif image and can also be an swf file. We will discuss this later on. Next, let’s declare our variables and imports. It’s important you understand variable scoping. private means that the variable is accessible within that class while public means that it can be accessed from outside i.e after compilation, you can access it from mxml or even from actionscript outside the class. Our variables here are private:

import mx.containers.Panel;
import mx.events.FlexEvent;
import flash.events.*;
import flash.ui.Mouse;
import mx.managers.CursorManager;
import flash.display.Graphics;
import mx.core.UIComponent;
private var edgeOffset:Number;
private var originalWidth:Number;
private var leftGrip:UIComponent;
private var lowestWidth:Number = 100;

lowestWidth is the minimum width that our custom component can attain. leftGrip is a dummy UIcomponent, not visible that the user mouses over for us to know that he’s on the edge of the Adjustable component. This UIcomponent is very important as we use it to listen and get mouse events to control the base panel. Let’s draw the leftGrip and place it in the panel. We do all our transactions in the createChildren() function. Please observe the code lines. The override protected means it should override the base class’s createChildern function, which is the function that creates all the assets and parts of the component. It’s a reserved function of all Actionscript UIComponents:

super.createChildren();
leftGrip = new UIComponent();
leftGrip.width = 10;
leftGrip.height = height;          ?
var g:Graphics = leftGrip.graphics;
g.clear();
g.beginFill(0xFFFFFF, 0);
g.drawRect(0, 0, 10, height);
g.endFill();
leftGrip.move(unscaledWidth-10, 0);
rawChildren.addChild(leftGrip);

First thing is to call the super’s (base panel class) createChildren() so the panel is formed normally! next we create an instance of the leftGrip UIComponent with the new() method, assign it a width of 10 pixels. Remember it’s this object that helps us know when the user mouses over the edge of our Adjustable component so we give it a width of 10. Then draw a graphics on it so it has a content which is declared simply as “g”. We draw on g and fill it with white color but leave it transparent (0xFFFFFF, 0) so the user doesnt see it. To make it visible, enter a value from 0.1 to 1 instead of the zero after the color. Finally we positioned and added it to the leftGrip object so it can receive mouse events and report to us. Next, we need to add event listeners to the dummy object called leftGrip so we know when to adjust our component width, which is our aim. To do that, we have:

leftGrip.addEventListener(MouseEvent.MOUSE_DOWN, resizeLeft);
            leftGrip.addEventListener(MouseEvent.MOUSE_OVER,
                function (event:MouseEvent):void{
                    CursorManager.setCursor(leftMouse);
                });
            leftGrip.addEventListener(MouseEvent.MOUSE_OUT,
                function (event:MouseEvent):void{
                    CursorManager.removeCursor(CursorManager.currentCursorID);
                });

The first line adds an event listener called MOUSE_DOWN to our dummy leftGrip object so it executes the resizeLeft function whenever the user clicks and holds down the mouse over the dummy. We will refer to this resizeLeft function later on. Next is the mouse over listener which simply changes the mouse to our leftMouse image class we referred to earlier on. So when the user mouses over that area, the mouse changes to the black arrow image. We use a new AS3.0 class called CursorManager to do this. When the user moves the mouse out of that area, we change it to the default cursor by removing the current cursor which is the black arrow. Now let’s consider the resizeLeft function that gets executed when the user mouses down on our dummy:

protected function resizeLeft(event:MouseEvent):void{
            CursorManager.setCursor(leftMouse);
            originalWidth = width;
            edgeOffset = parent.mouseX;
            systemManager.addEventListener(MouseEvent.MOUSE_MOVE, doLeft, true);
            systemManager.addEventListener(MouseEvent.MOUSE_UP, stopResizing, true);
            systemManager.stage.addEventListener(Event.MOUSE_LEAVE, stopResizing);
        }

First we ensure that the mouse is set to our black arrow using the CursorManager, then capture the current width of the component and store it in our variable “originalWidth” so all we do as the user moves the mouse is add or subtract from it to set the new width. we also capture the mouse’s X position which is stored in edgeOffset. Note this position is taken with respect to the parent’s coordinate. Now we simply add a new set of mouse event listeners using the systemManager. This just ensures that only this mouse event is attended to because there’s just one systemManager in a running flash application, same with stage. We have just one stage. Lets now consider how the adjustment is done when the user drags the mouse after clicking, which is the doLeft function.

protected function doLeft(event:MouseEvent):void{
            if ((originalWidth + (parent.mouseX - edgeOffset)) > lowestWidth){
                width = originalWidth + (parent.mouseX - edgeOffset);
                leftGrip.move(unscaledWidth-10, 0);
            }
        }

We check if the originalWidth plus or minus the new change is greater than the lowestWidth we want our component to attain. If not, then nothing is done but if it is still greater than that, then we adjust our component’s width as follows: Add the originalWidth to the difference between the parent’s new X position and the new one which is the actual drag difference that the user did. Simple logic! Then we reposition our leftGrip dummy to the edge of the panel again.

protected function stopResizing(event:Event):void{
            CursorManager.removeCursor(CursorManager.currentCursorID);
            systemManager.removeEventListener(MouseEvent.MOUSE_MOVE, doLeft, true);
            systemManager.removeEventListener(MouseEvent.MOUSE_UP, stopResizing, true);
            systemManager.stage.removeEventListener(Event.MOUSE_LEAVE, stopResizing);
        }

The stopResizing removes all the systemManager listeners we registered earlier on and sets the mouse icon to the default by removing the current one, which is our black horizontal arrow. That is all, compile your application and FlexBuilder will generate an swc for you which will include your Adjustable component. Next, create a new Flex project and add the location of the new Adjustable swc file in the project’s path. Go to the view and you’ll see our new Adjustable panel as one of the components under the Custom folder in your components pane. Drag it and drop on the canvas and use it as you would a normal panel. Try and adjust it’s width from the far right.

Conclusion
This component has been designed to add the width adjustment functionality to a base panel class found in Flex. Similar method can be used to extend other UI components or develop new ones. We leave it to the reader to extend this functionality further by adding the height adjustment to it as well.

Entry filed under: Flex. Tags: .

Simple Flex Tutorial FlexKeypad

2 Komentar Add your own

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


Kunjungan

  • 380,535 kunjungan
Maret 2008
S S R K J S M
« Feb   Mei »
 12
3456789
10111213141516
17181920212223
24252627282930
31  

test


%d blogger menyukai ini: