Sunday, February 14, 2010

Dynamically creating and adding components in your application

Hello Everyone!

This post is mostly for the people who are new to Adobe Flex and have only been working with mxml till now.
Today , we would be talking about how to create and add visual elements , like buttons, panels, html components etc onto you application and how to handle clicks, double clicks in short any kind of mouse events.

Creating Components

Every component in mxml file is actually a class in itself.So all you really need to do is create a new object of this class , and every property ,event , and method of the component you see in mxml can be accessed and used using ActionScript 3.0.

Lets say we want to create a button:
so the code for the same is as following:

var myButton:Button = new Button();//creating a new object
myButton.x=10;//setting the x of the button
myButton.y=15;//setting the y coordinate of the button
myButton.label="I am a button";//the text that appears on the button
//above line is almost like

So you see how easy was it to create and modify the attributes of the button.
Lets go on to the step where we would add it to the application.

Adding the button to the application UI

You can think of the whole as one big class where everything stays.This class has a default place called stage where it adds all the elements to be shown to the user as a part of the UI.
So all you need now is to instruct this class to add the newly created button onto its stage.To do this there is a function called addChild();

So what you would be doing is in the script tag of the mxml you would be using this function and pass the button as a parameter to this function , to finally add the button on the UI.
So the code now will look something like:


public function init():void
//code here to initiliaze the button with id myButton.

this.addChild(myButton);//this line is like the final mark saying that yes I want the button to be shown to the user on the specified x and y coordinates



Passing the stage to other classes
Using the above code you can add the button to the stage only in the same class as the windowed application.What if you want to add the button to the stage in some other class?
For that you can pass the stage to other classes and in those classes add the button.
Lets say we have a class called MyClass which has the following constructor

public function MyClass(stage:Object):void
//code to initialize the button

and in the script tag you would do

var myObj:MyClass=new MyClass(this);

The above code is passing the object of WindowedApplication to the object of MyClass and in the constructor , a new button is being created and being added to the WindwedApplication.

With some more experiments you can try some pretty cool stuff by passing the stage and adding or removing elements form the stage from other classes.

Keep Flexing Ppl!