You are on page 1of 46

Flex Tutorials

Adobe flex builder application development tool.

Benefits of flex:

1. Its free and open source framework

2. Used to develop cross platform rich internet applications based on flash platform.

3. Flex applications provide real time rich user-experience.

4. Much more faster than traditional html based applications.

5. Loads only the required content from the server hence reduces the load on servers a lot.

6. Flex puts very less overhead to the database, and network.

7. Developing user interfaces are now easy using Adobe Flex Builder .
8. Unlike AJAX, flex applications looks and reacts the same way on each browser and platform.

1. Introducing Flex
lex is a programming language developed on adobe technology to enhance the users capability in
building rich internet applications. This latest adobe technology possesses all flash features. Flex is
embedded with two languages MXML and Action Script respectively. Among all known scripting
languages Action Script is one of them that comes along with Flex SDK(software development kit).

MXML is a tag based language while Action Script is a flash language and developers pro to oop's
(object oriented programming) will face no problem with this flash language.

Flex is a programming language developed on adobe technology to enhance the users capability in
building rich internet applications. This latest adobe technology possesses all flash features. Flex is
embedded with two languages MXML and Action Script respectively. Among all known scripting
languages Action Script is one of them that comes along with Flex SDK(software development kit).
MXML is a tag based language while Action Script is a flash language and developers pro to oop's (object
oriented programming) will face no problem with this flash language.

Server the compilation of flex source file  is adobe's Application server which is a J2EE application.
Flex coding is done with an XML based language known as MXML  and like Flash applications, Flex codes
too are compiled into a file having SWF format called ShockWave Flash files. These SWF  files are
executed with stand-alone Adobe's Flash Players, and can also be directly executed in browsers that
have Adobe Flash Player Plug-in installed. 

For developing Flex applications, Adobe has launched Flex builder that works in Eclipse environment.
Flex 3 builder is the latest and can be freely downloaded from Adobe's official website. But building Flex
applications on Flex builder in eclipse environment is a cumbersome  job to perform, one reason is that
using eclipse with flex builder plugin will make it very slow, also lot of time is been taken in
compilation. To get rid of this problem there is another way to compile Flex application which works on
Apache Ant technology. Apache's this technology is used to make a build.xml file that will be used later
to call the flex compiler in deploying the flex application.

Flex languages

Flex coding involves two different languages MXML and ActionScript respectively.

MXML is an extended form of  XML and is a tag based language, and therefore it is called an
XML-based markup language.

Program files coded with mxml language possess '.mxml'  extensions.

MXML used along with ActionScript  provide tags to devise GUI (graphical user interface)
component and is also used to get access to data on servers. MXML facilitates its users with its
data binding services. 

HTML and MXML both provide tags but the difference is that MXML consists of several new
tags like TabNavigators and Accordions and many more that also enable users to get any web
service connection. A MXML file is converted into a SWF file that runs on a Flash Player or on
a browser which has Adobe Flash Player Plug-in installed in it.

ActionScript a flash language is an implementation of ECMA Script and is similar to OOP


based JavaScript. In Adobe Flash Player this is the main programming tool. It consists of built-in
objects  and functions, and allows its users to build their own objects and functions. With this
strong tool one can extend its competency in creating RIAs. Its coding is done inside the tag
<mx:Script/>.

We create ActionScript files and call them inside the main MXML file with either 'source'
attribute of <mx:Script> tag or with 'include' statement inside <mx:Script> tag by passing
the relative path names of ActionScript files in these attributes.

Each and  every ActionScript file should be saved with '.as' extension
2. Downloading and Installing Flex
Downloading and Installing Flex Builder
Refer: http://www.roseindia.net/flex/flex_builder_ide.shtml
4. Flex Example
Compiling MXML application 

Generating a shock wave file.

Compilation of flex file is done by the flex compiler that comes along with the flex software kit.

Flex compiler is located inside the flex bin folder with name mxmlc.exe. For compiling our Flex
file we need to do two things,

first is setting the flex-sdk path up to its bin 'folder', i.e.,  C:\Program Files\flexsdk3.0.0.477\bin 
in the 'Path' variable of System Variables under Environment Variables. S

econd is to locate the relative path of the compiler, i.e., C:\Program


Files\flexsdk3.0.0.477\bin\mxmlc.exe correctly in your ant build file.

Now after these measures taken, your compiler will be detected by the Ant Utility and will be
called to compile the MXML file in to SWF file.

Your final .swf file will be executed in browser that has Flash Player plugin installed.

Flex User Interface Component Example

Flex User Interface Component Example In Flex two types of user interface components:
Controls and Containers are used. 

Controls are generally located inside the Containers. Controls consist of Customizable features
like fonts and styles. For a Control declaration  API of MXML language  is used. Table below
lists the Control elements used in Flex programming.

• NumericStepper
• Button 
• PopUpButton
• CheckBox

• ColorPicker
PopUpMenuButton
• ComboBox
• ProgressBar
• DataGrid
• RadioButton
• DateChooser
• RichTextEditor
• DateField
• Text
• HSlider
• TextArea
• HorizontalList
• TextInput
• Image
• TileList
• Label
• Tree
• LinkButton
• VSlider
• List
• VideoDisplay
Layout Containers Navigator Containers
• Canvas • ModuleLoader • Accordian
• ControlBar • Panel • ButtonBar
• Form • Spacer • LinkBar
• FormHeading • Tile • MenuBar
• Grid • TitleWindow • TabBar
• Hbox • Vbox • TabNavigator
• HDividedBox • VDividedBox • ToggleButtonBar
• HRule • VRule • ViewStack

Eve.mxml

<?xml version = '1.0' encoding = 'ISO-8859-1'?>
  <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">

    <mx:Label id = "eve"/>
    <mx:TextInput text = 'Click me to label eve' 
      click = 'eve.text = String("Rachel Weisz")'/>

</mx:Application>

Eve.swf

   

In the program, an id property inside the Control and Container tags are used  to establish
interactivity in them. This Flex code has XML declaration statement that defines the XML
version. The code contains a root tag <mx:Application>. Now a 'Panel' layout Container
maintains the positioning of its components like ViewStack container and Canvas container and
also of Label and Button Controls. Canvas Containers are placed inside the ViewStack Container
and so they are called as child components of the ViewStack Container. Canvas Containers with
their 'id' property are switched with the specific Button  Controls in which they are called. Here
in switching Canvas Containers, the ViewStack 'id'  is used because these Canvas Containers are
inside the ViewStack Container and are said to be its child Components.

Whenever any Canvas gets switched through a Button click, the 'text' attribute value under the
Label Control of  Canvas Container is demonstrated.

Scarab.mxml
<?xml version = "1.0" encoding = "utf-8"?>
  <mx:Application xmlns:mx = "http://www.adobe.com/2006/mxml">

    <mx:Panel title = 'My Flex Window' width = "30%" 
                    height = "30%">
    <mx:ViewStack id = 'RachelWeisz' width = '100%' 
                    height = '100%'> 
      
      <mx:Canvas id = 'Rath' backgroundColor = '#FFFCCC'>
        <mx:Label text = 'Welcome to future' 
                  color = 'green'/>
      </mx:Canvas>

      <mx:Canvas id = 'Armon' backgroundColor = '#CCCCFF'>
        <mx:Label text = 'well! some body is angry' 
                      color = 'red'/>
      </mx:Canvas>
  
    </mx:ViewStack> 
    </mx:Panel>

    <mx:HBox>
      <mx:Button label = 'Button 1' click = 
              "RachelWeisz.selectedChild = Rath"/>
      <mx:Button label = 'Button 2' click = 
              "RachelWeisz.selectedChild = Armon"/>
    </mx:HBox>

</mx:Application>

Scarab.swf run on browser

     

Action Script in Flex

Example below shows the use of Action Script inside the MXML code. Action Script coding is
done inside <mx:Script> tags.  

Morpheus.mxml
<?xml version = '1.0' encoding = 'utf-8'?>
  <mx:Application xmlns:mx = 'http://www.adobe.com/2006/mxml'>
    <mx:Script>
          <![CDATA[
            
              public function Trinity():void{
                  Niobe.text = String('Neo - Why am I here'); 
                    Bane.label = String('GhostGhostn'); 
                }
              
              ]]>
    </mx:Script>
        
             <mx:Label id = 'Niobe'/>
             <mx:Button id = 'Bane' click = 'Trinity()'/> 
              
</mx:Application>

Morpheus.swf

  

5. Eclipse flex ant coding example

6. Compiling MXML files with FlexBuilder

On this page, you will be guided, to code and compile a flex application on adobe Flex Builder.
This adobe product is eclipse based therefore many of eclipse features can be seen inside the flex
builder.
I have the evaluation copy of flex builder and using this only, i am going to guide you. So before
starting you too have this adobe ide installed in your system, if not then first visit the link below
and get Flex Builder.

http://www.roseindia.net/flex/flex_builder_ide.shtml

Now i after getting flex builder i know you are ready for learning the coding and compiling
process of flex on adobe flex builder.
So lets start, first trigger the binary file of flex builder.
 

After the launcher file is triggered, flex builder opens.


            

When flex builder ide main page opens close the OutLine tab, Problems tab and Flex Start
Page tab. This will provide more coding space.
            

 Now after closing the above three window tabs, you will get the ide main page view as below
shown.
   

Now for coding a flex application first we have to create a flex project, like we create for Java
and C/C++ in eclipse. For this click File -> New -> Flex Project.

After this a New Flex Project window opens. In the Project name: column type the name of
your project , here i have written neo as project name. After that click on Finish button.
  

   

   

 
After this a project with name neo comes in your Flex Navigator window and by default a
neo.mxml file is opened.

       

Now if you want you can start coding with neo.mxml file or you can open another mxml file
too. For this click on 
File -> New -> MXML Application

       

or right click on your flex project neo and click on File -> New -> MXML Application.

         

After this a New MXML Application window opens. On this, type your file name in Filename:
column and click Finish. Here i have written my file name as rachel, so a MXML application
with name rachel.mxml will be created and opened.
 

After this you can start coding on the new file rachel.mxml.
For getting maximum coding space minimize the Flex Navigator window.

After this i coded an application in which i have added wipe effect in four flex control buttons.
You all have to just copy code from here or download at the end of the page and paste the code
in your mxml application.
rachel.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">

  <mx:WipeDown id = 'wipe_down' />
  <mx:WipeLeft id = 'wipe_Left' />
  <mx:WipeRight id = 'wipe_Right' />
  <mx:WipeUp id = 'wipe_Up' />

  <mx:Style>
    .baadshah {color : #00FF00}
    Panel{font-size : 18pt}
    Button{font-size : 10pt}
  </mx:Style>
  
  <mx:Panel title = 'Baadshah Khan' titleStyleName="baadshah">
  

  <mx:ControlBar horizontalAlign = 'center'>
  
      <mx:Button label = 'Rachel Weisz' rollOverEffect = 'wipe_down' color="#9
90033" />
      <mx:Button label = 'Angelina Jolie ' rollOverEffect = 'wipe_Left' color=
"#6600FF" />
      <mx:Button label = 'Halle Berry' rollOverEffect = 'wipe_Right' color="#3
36600" />
      <mx:Button label = 'Roseindia.net' rollOverEffect = 'wipe_Up' color="#00
0099" />
      
  </mx:ControlBar>

  
  </mx:Panel>
</mx:Application>

For compiling press F11 or click on Run -> Run Rachel or Run -> Debug Rachel. 

                       

                       

After this on your default browser, following out is displayed. 


This output is your swf file which is executed. The output swf is generated inside your project
bin-debug folder.

rachel.swf

       .
       

So like this a flex application is coded, compiled and at last is executed inside the Flex Builder.
Flex Builder contains Adobe Flash Player inside Player\10\win folder, you can switch here
and execute the FlashPlayer.exe. After this a window shown below opens.

You can drag-drop your swf file from the neo\bin-debug  folder into the Flash Player and the
rachel.swf file will be executed.

Now you know how to code, compile an flex application and also to execute the swf file with
browser as well as with the flash player, congrats.
7. Flex Combo Box example
In this tutorial page you will be taught to utilize ComboBox control inside your flex file. In the
example you will learn to build two ComboBox controls. The Example below shows combo
boxes with nicely formatted string data, so here you will be also taught to do the graphical works
on flex visual component. 

The following code demonstrates the ComboBox control working example. This control shows
the drop-down list of data you passed as String inside it.

 combo.mxml

<?xml version = '1.0' encoding = 'utf-8'?>
<mx:Application xmlns:mx = 'http://www.adobe.com/2006/mxml'>
  <mx:Panel title = 'Megara (Hercules)' width = '70%' 
            height = '40%' color = '#FFFFCF'>
    <mx:Canvas backgroundColor = '#CCCCFC' width = 
                  '100%' height = '100%'>

      <mx:ComboBox color = 'red'>
        <mx:dataProvider>
          <mx:Array>
            <mx:String> Neo/ Thomas Anderson 
                </mx:String>
            <mx:String> Trinity/ Carrie-Anne Moss
                 </mx:String>
            <mx:String> Eve/ Rachel Weisz 
                </mx:String>
          </mx:Array>
        </mx:dataProvider>
        </mx:ComboBox>

      <mx:ComboBox x = '200' color = 'green'> 
        <mx:dataProvider>
          <mx:Array>
            <mx:String> Snow White - Adriana Caselotti
                 </mx:String>
            <mx:String> Aurora - Mary Costa </mx:String>
            <mx:String> Ariel - Jodi Benson </mx:String>
          </mx:Array>
        </mx:dataProvider>
      </mx:ComboBox>
  
    </mx:Canvas>
  </mx:Panel>

</mx:Application>

 
combo.swf

 8. Flex combobox selecteditem


n this tutorial page you will learn how to utilize the selectedItem property in flex, for getting the
details associated to items inside the flex combo box control. Below example contains a flex
combo box control with id value combo. This flex control contains eleven items and with
selectedItem property  details of each item is published inside the flex TextArea control under
flex Panel control background. Property selectedItem returns the string value of the item, that
means, name of the item is returned with which the item is included in the combo box item list. 

Syntax for using the property


ComboBox_id_value.selectedItem

Example in the tutorial page contains some links to well trusted web site pages, with which you
can enrich your knowledge.

oksoo.mxml

<?xml version = '1.0' encoding = 'utf-8'?>
<mx:Application
  xmlns:mx = 'http://www.adobe.com/2006/mxml'
>

  
  <mx:Script>
    
  <!-- 
    function Item_detail is setting combo box 
    item information in to each item
  -->
  
  public function Item_detail(event:Event):void{
        
    if(combo.selectedItem == 'Roseindia'){
      txt.text = 'Software development company'
      link_0.visible = true;
    }
    if(combo.selectedItem == 'Ajax'){
      txt.text = 'Asynchronous JavaScript' 
             + ' and XML is used to fetch' 
             + ' the data from web server' 
             + ' without refreshing the whole'
             + ' page.';
      link_6.visible = true;
    }
    if(combo.selectedItem == 'Dojo'){
      txt.text = 'Another great' 
            + ' framework for developing'
            + ' ajax based applications.';
      link_7.visible = true;
    }
    if(combo.selectedItem == 'Spring'){
      txt.text = 'Spring Framework Install -' 
            + ' a quick tutorial to install' 
            + ' Spring Framework on your' 
            + ' development environment.';
      link_8.visible = true;
    }
    if(combo.selectedItem == 'JSF'){
      txt.text = 'JSF tutorials we will' 
            + ' describe you how to' 
            + ' implement all theoretical'
            + ' concepts of JSF in developing'
            + ' robust  JSF web application.';
      link_9.visible = true;
    }
    if(combo.selectedItem == 'Combo Box'){
      txt.text = 'A Flex control'
      link_10.visible = true;
    }
    if(combo.selectedItem == 'Flex'){
      txt.text = 'Adobe technology to enhance the'
             + ' users capability in building'
             + ' rich internet applications.';
      link_1.visible = true;
    }
    if(combo.selectedItem == 'Ant'){
      txt.text = "Apache's Ant technology, which" 
             + ' is a mean to build any'
             + ' programming language projects.';
      link_2.visible = true;
    }
    if(combo.selectedItem == 'Core Java'){
      txt.text = 'Java is great programming language'
            +  ' for the development of enterprise'
            + 'grade applications.';
      link_3.visible = true;
    }
    if(combo.selectedItem == 'Mysql'){
      txt.text = 'MySQL tutorial is available at'
            + ' free of cost and 365x24 days'
            + ' for your help';
      link_4.visible = true;
    }
    if(combo.selectedItem == 'J2EE'){
      txt.text = 'Application server was developed'
          + ' to support for developing the'
          + ' enterprise applications for security'
          + ' and state maintenance with the data'
          + ' base and persistence.';
      link_5.visible = true;
    }
  }
    
  public function clearData():void{
      txt.text = '';
  }
  
  </mx:Script>

  
  
  <!-- functions created for providing item links --> 
  
  
<mx:Script>

  public function roseindia(event:Event):void{
    var url_0:URLRequest;
url_0 = new URLRequest('http://www.roseindia.net/');
    navigateToURL(url_0);
  }
  public function Flex(event:Event):void{
    var url_1:URLRequest;
url_1 = new URLRequest('http://www.roseindia.net/flex/');
    navigateToURL(url_1);
  }
  public function Ant(event:Event):void{
    var url_2:URLRequest;
url_2 = new URLRequest('http://www.roseindia.net/tutorials/ant/');
    navigateToURL(url_2);
  }
  public function Core_Java(event:Event):void{
    var url_3:URLRequest;
url_3 = new URLRequest('http://www.roseindia.net/java/');
    navigateToURL(url_3);
  }
  public function Mysql(event:Event):void{
    var url_4:URLRequest;
url_4 = new URLRequest('http://www.roseindia.net/mysql/');
    navigateToURL(url_4);
  }
  public function J2EE(event:Event):void{
    var url_5:URLRequest;
url_5 = new URLRequest('http://www.roseindia.net/ejb/');
    navigateToURL(url_5);
  }
  public function Ajax(event:Event):void{
    var url_6:URLRequest;
url_6 = new URLRequest('http://www.roseindia.net/ajax/');
    navigateToURL(url_6);
  }
  public function Dojo(event:Event):void{
    var url_7:URLRequest;
url_7 = new URLRequest('http://www.roseindia.net/dojo/');
    navigateToURL(url_7);
  }
  public function Spring(event:Event):void{
    var url_8:URLRequest;
url_8 = new URLRequest('http://www.roseindia.net/spring/');
    navigateToURL(url_8);
  }
  public function JSF(event:Event):void{
    var url_9:URLRequest;
url_9 = new URLRequest('http://www.roseindia.net/jsf/');
    navigateToURL(url_9);
  }
  public function Combo_Box(event:Event):void{
    var url_10:URLRequest;
url_10 = new URLRequest('http://www.livetechtalk.com/');
    navigateToURL(url_10);

  }
    public function Dating(event:Event):void{
      var url_11:URLRequest;
url_11 = new URLRequest('http://www.onedatingtips.com/');
    navigateToURL(url_11);
    }
  
</mx:Script>
    
    
    
    
<mx:Script>
  
  <!-- 
    function clickEventListener is a 
    handler function function inside which 
    mouse click event is added into 
    the Link Buttons
  -->
  public function clickEventListener():void{
      
    link_0.addEventListener(MouseEvent.CLICK, roseindia);
    link_1.addEventListener(MouseEvent.CLICK, Flex);
    link_2.addEventListener(MouseEvent.CLICK, Ant);
    link_3.addEventListener(MouseEvent.CLICK, Core_Java);
    link_4.addEventListener(MouseEvent.CLICK, Mysql);
    link_5.addEventListener(MouseEvent.CLICK, J2EE);
    link_6.addEventListener(MouseEvent.CLICK, Ajax);
    link_7.addEventListener(MouseEvent.CLICK, Dojo);
    link_8.addEventListener(MouseEvent.CLICK, Spring);
    link_9.addEventListener(MouseEvent.CLICK, JSF);
    link_10.addEventListener(MouseEvent.CLICK, Combo_Box);
    
  }

<!-- void function vanish vanishes all the link buttons 
  on the application background
-->
  public function vanish():void{
    link_0.visible = false;
    link_1.visible = false;
    link_2.visible = false;
    link_3.visible = false;
    link_4.visible = false;
    link_5.visible = false;
    link_6.visible = false;
    link_7.visible = false;
    link_8.visible = false;
    link_9.visible = false;
    link_10.visible = false;
  }

</mx:Script>

    
    
<!-- 
  <mx:Style>, a cascading style sheet component 
  used for setting styles of flex components 
-->    
    
<mx:Style>
  .baadshah {color : #3399FF}
     Text {font-size : 12pt}
     Text {fontStyle : bold}
     TextArea {color : #330099}
     TextArea {font-size : 12pt}
     LinkButton {color : #660066}
</mx:Style>
    

<!-- flex panel control -->  
<mx:Panel 
  title = 'Roseindia panel background' 
  width = '100%' height = '100%'
  color = '#660000'
>
    
    <!-- flexx combo box control -->
  <mx:ComboBox 
    mouseOver = 'clickEventListener()'  
    valueCommit= 'clearData()' 
    id = 'combo' 
        
    change = 'Item_detail(event)'>
      <mx:String>Combo Box</mx:String>
      <mx:String></mx:String>
      <mx:String>Roseindia</mx:String>
      <mx:String>Flex</mx:String>
      <mx:String>Ant</mx:String>
      <mx:String>Core Java</mx:String>
      <mx:String>Mysql</mx:String>
      <mx:String>J2EE</mx:String>
      <mx:String>Ajax</mx:String>
      <mx:String>Dojo</mx:String>
      <mx:String>Spring</mx:String>
      <mx:String>JSF</mx:String>
            
      
  </mx:ComboBox>
    
    
  <mx:ControlBar horizontalAlign = 'center'>
      <mx:Text text = '{combo.selectedItem}' /> 
  </mx:ControlBar>
  
  <mx:TextArea
    id = 'txt' 
    styleName = 'baadshah'
    width = '60%' height = '40%'
    color = '#330000'  
  />
    
    
<mx:HBox styleName = 'baadshah' >
  <mx:VBox>
    <mx:LinkButton 
        id = 'link_0' 
        label = 'Roseindia' visible = 'false'/> 
    <mx:LinkButton 
      id = 'link_1' 
      label = 'Flex' visible = 'false'/> 
  </mx:VBox>
  <mx:VBox>
    <mx:LinkButton 
      id = 'link_2' 
      label = 'Ant' visible = 'false'/> 
    <mx:LinkButton 
      id = 'link_3' 
      label = 'Core Java' visible = 'false'/> 
    </mx:VBox>
  <mx:VBox>
    <mx:LinkButton 
      id = 'link_4' 
      label = 'Mysql' visible = 'false'/> 
    <mx:LinkButton 
      id = 'link_5' 
      label = 'J2EE' visible = 'false'/> 
  </mx:VBox>
  <mx:VBox>
    <mx:LinkButton 
      id = 'link_6' 
      label = 'Ajax' visible = 'false'/> 
    <mx:LinkButton 
      id = 'link_7' 
      label = 'Dojo' visible = 'false'/> 
  </mx:VBox>
  <mx:VBox>
    <mx:LinkButton 
      id = 'link_8' 
      label = 'Spring' visible = 'false'/> 
    <mx:LinkButton 
      id = 'link_9' 
      label = 'JSF' visible = 'false'/> 
  </mx:VBox>
  <mx:VBox>
    <mx:LinkButton 
      id = 'link_10' 
      label = 'Combo Box' 
      visible = 'false'
      mouseOver = 'Dating(event)'
    /> 
  </mx:VBox>
</mx:HBox>
    <mx:ControlBar horizontalAlign = 'center'>
      <mx:Button 
        label = 'vanish' 
        click = 'vanish()'
        color = '#FF00FF'  
      />
    </mx:ControlBar>
  
</mx:Panel>
</mx:Application>

oksoo.swf
9. Flex checkbox control example
The page provides illustration about the working of flex checkbox control. Example is based on
registration for online training courses. On the registration form, trainee check marks the courses
in which he/she is interested. After that it clicks on Post button to send its request. For check
marking flex check boxes are created and for posting flex button control is used. Functionalities
like getting marked courses data and processing it, is achieved via two void functions
Course_selected and Request_Process, created in the example.

Flex check boxes controls possess a box and a label. On the box, check marks are marked and
with label, information regarding  the check box control is demonstrated.

Syntax for creating CheckBox control :


        <mx:CheckBox/>

Onlineline_Training.mxml

<?xml version = '1.0' encoding = 'ISO-8859-1'?>
<mx:Application 
  xmlns:mx = 'http://www.adobe.com/2006/mxml'
  backgroundColor = '0x000000'
  backgroundGradientColors = '[#330033, #660000]'
>

  <mx:Script>
    import mx.controls.*;

    <!-- method adds text to TextArea control -->    
    public function Course_Selected():void{
      txt.text = '';  
      
      if(Java.selected)
      txt.text += 'Java' + '\n';
      if(Advanced_Java.selected)
      txt.text += 'Advanced Java Training' + '\n';
      if(Mysql.selected)
      txt.text += 'Mysql Training' + '\n';
      if(JSP.selected)
      txt.text += 'JSP Training' + '\n';
      if(Hibernate.selected)
      txt.text += 'Hibernate Training' + '\n';
      if(Servlet.selected)
      txt.text += 'Servlet Training' + '\n';
    }
    
    
    <!-- function process the user checks result --> 
    public function Request_Process():void{
      if(txt.text == '')
      Alert.show('Request rejected' 
        + '\n' + 'no course selected');
      else
      Alert.show('Request send' + '\n' 
        + 'soon u will get a call from company');
    }
  
  </mx:Script>
  
  <mx:Panel 
    title = 'Roseindia Online Training Service'
    width = '50%' height = '60%'
    paddingBottom = '10' paddingTop = '10' 
    paddingLeft = '10' paddingRight = '10' 
    color= '#CCCCCC' 
    borderAlpha='0.20'
  >
    <mx:HBox>
    <mx:VBox color = '#330033'>
      <mx:CheckBox 
          id = 'Java'
          label = 'Core Java Training'
          click = 'Course_Selected()'
          iconColor= '#66FF33'/>
      <mx:CheckBox
          id = 'Advanced_Java'
          label = 'Advanced Java Training'
          click = 'Course_Selected()'
          iconColor = '#3300FF'/>
      <mx:CheckBox
          id = 'Mysql'
          label = 'Mysql Training'
          click = 'Course_Selected()'
          iconColor = '#660000'/>
      <mx:CheckBox
          id = 'JSP'
          label = 'JSP Training'
          click = 'Course_Selected()'
          iconColor = '#336600'/>
      <mx:CheckBox
          id = 'Hibernate'
          label = 'Hibernate Training'
          click = 'Course_Selected()'
          iconColor = '#33CC66'/>
      <mx:CheckBox
          id = 'Servlet'
          label = 'Servlet Training'
          click = 'Course_Selected()'
          iconColor = '#330000'/>
    </mx:VBox>
    
    <mx:VBox width = '100%' height = '100%'>
      <mx:Label text = 'Shopping items list'/>
      <mx:Button 
        id = 'item_delivery'  
        label = 'Post' 
        click = 'Request_Process()'
        color = '#000000'
        y = '200'
      />
      <mx:TextArea 
        id = 'txt' 
        width = '100%' height = '100%'
        verticalScrollPolicy = 'off' 
        editable = 'false'
        color = '#000033'
      />   
    </mx:VBox>
    </mx:HBox>
     
  </mx:Panel>

</mx:Application>

Onlineline_Training.swf
10. Flex wipe behavior example
Code below shows the implementation of wipe behavior in buttons through its rollOverEffect
property. The first button wipes from left to right and the second one from right to left. This
wiping is mouse event based and therefore it will continue to wipe till the mouse arrow is over
the button. 

wipe.mxml

<?xml version = '1.0' encoding = 'ISO-8859-
1'?>
<mx:Application xmlns:mx = 'http://www.adobe.
com/2006/mxml'>

    <mx:WipeLeft id = 'eve' duration = '1000'
/>
    <mx:WipeRight id = 'bracelet' duration = 
'1000'/>

    <mx:Button 
      label = 'The One, game protagonist and 
the character'
         rollOverEffect = '{eve}'/>
    <mx:Button 
      label = "Neo's love interest and First 
mate" 
        rollOverEffect = '{bracelet}'/>

</mx:Application> 

wipe.swf

11. Flex Alert Box example


Alert box is a dialog box that appears on window with some message and stays rigid until the
event associated with it is not done. Alert Box is also referred to as pop-up window. 

Among these two words Alert & box, Alert is a class defined inside the mx.controls package.
The pop-up window appears when .show() method of Alert class is called. Programmer can write
its message inside the method parenthesis, method displays programmers message as string on
the opened pop-up window that contains a string title  'Alert'.

 alert.mxml

<?xml version = '1.0' encoding = 'ISO-8859-1'?>
<mx:Application xmlns:mx = 'http://www.adobe.com/2006/mxml'>

  <mx:Panel title = 'Action Script Alert event example' 
          width = '100%' height = '100%'>

    <mx:Script>
      import mx.controls.Alert;
      import mx.events.CloseEvent; 
    </mx:Script>
      
      <mx:Button label = 'Click' click = 'Alert.show("Fire A
lert!!")'/>

    <mx:Script>
      public function method1():void{
        Alert.show('want to play', 'message', 3, this, metho
d2)
      }

      public function method2(event:CloseEvent):void{
        if(event.detail == Alert.YES)
eve.text = "You answer is 'yes' so your player ID is: "   + 
event.detail;
        else      
eve.text = "You answer is 'No' but still if want to play the
n your player ID is: "
             + event.detail;
        }
    </mx:Script>

      <mx:Button label = 'Button' click = 'method1()'/>
      <mx:Label id = 'eve' fontWeight = 'bold' color = 'gree
n'/>

  </mx:Panel>

</mx:Application>

alert.swf

12. Flex Validator example


Code below shows Flex validator component example. With these components different types of
data are get validated with appropriate validators. The provided flex feature is mostly used in
validating the user ids,  email addresses and passwords. 

In the example validator for email and phone numbers are made. When the user writes, data
validator checks the syntax and type of data entered and if the data entered is found to be wrong, 
the corresponding validator generates error message  in red text format.
Similarly many different types of validators can be created and that you will be going to learn
soon.  

validator.mxml

<?xml version = '1.0' encoding = 'ISO-8859-
1'?>
<mx:Application xmlns:mx = 'http://www.adobe
.com/2006/mxml'>

    <mx:PhoneNumberValidator source = '{phon
eNumber}' 
                     property = 'text'/>
    <mx:EmailValidator source = '{EmailId}' 
                     property = 'text'/>

    <mx:Panel title = 'Flex Validator Contro
l'>
    
      <mx:TextInput id = 'phoneNumber' 
          text = 'Your valid phone number.'/
>
      <mx:TextInput id = 'EmailId' 
          text = 'baadshah@newstrackindia.co
m'/>
    
    </mx:Panel>

</mx:Application>

validator.swf

13. Flex Tab Navigator example


Under mx.containers package TabNavigator class is present and under this class
TabNavigator container is present.
Tab Navigators are Navigator containers of flex. In the following code, three tabs have been
created using flex Layout container VBox. In the example wipe effect behavior is also
demonstrated. 

navigator.mxml

<?xml version = '1.0' encoding = 'utf-8'?>
<mx:Application xmlns:mx = 'http://www.adobe.com/2006/mxml'>
  
  <mx:WipeLeft id = 'wipe_left'/>
  
    <mx:Panel title = 'Tab Navigators' width = '100%' height = '100%'>
      <mx:TabNavigator width = '100%' height = '100%'>
      
        <mx:VBox label = 'Panel 1' showEffect = '{wipe_left}'>
          <mx:Text text = 'You switched Panel1 Tab '  color = '#996600'/>
        </mx:VBox>
        
        <mx:VBox label = 'Panel 2' showEffect = '{wipe_left}'>
          <mx:Text text = 'You switched Panel2 Tab' color = '#FF9900'/>
        </mx:VBox>
        
        <mx:VBox label = 'Panel 3' showEffect = '{wipe_left}'>
          <mx:Text text = 'You switched Panel3 Tab' color = '#9966CC'/>
        </mx:VBox>
      
      </mx:TabNavigator>
    </mx:Panel>
    
</mx:Application>

navigator.swf
14. Flex Cascading Style Sheets example
Following code demonstrates the use of <mx:Style> tag.  Style definitions of this tag are implemented
on other GUI components like on Button controls. This implementation is done by using the class
selector, here class selector is used with name Alexander.

Like other flex components id attribute, class selector is the id attribute of style tag and acts as
its identifier. Under the tag, style statements for the flex components are coded. Further the
features defined through the statements are invoked in the components mostly in containers with
the styleName property. 
In the example below styles are implemented on flex  Button and Combo box controls.

cascade.mxml

<?xml version = '1.0' encoding = 'utf-8'?>
<mx:Application xmlns:mx = 'http://www.adobe
.com/2006/mxml'>
  
  <mx:Style>
    .Alexander {color : green}
    Button {font-size: 10pt}
  </mx:Style>
  
  <mx:Button label = 'Motorist' styleName = 
'Alexander'/>
  
  <mx:ComboBox id = 'combo' styleName = 'Ale
xander'>
    <mx:Button label = 'Teacher'/>
    <mx:Button label = 'Central Park carriag
e driver'/>
    <mx:Button label = 'Flower store worker'
/>
  </mx:ComboBox>
  
</mx:Application>

cascade.swf

15. Action Script 'source' attribute example


In the example below an action script file with .as extension has been imported in the main
Operations.mxml file. This .as file instance is brought through the source attribute in
<mx:Script> tags. 

Syntax for using 'source' attribute:-        

<mx:Script source  =  '     '> ...... </mx:Script>

In the imported action script file four functions are defined and they are called through the click
attribute property of buttons in the main mxml file. 

IncludedFile.as

public function addition(x:Number, y:Numb
er):Number {
return x + y;
}

public function product(x:Number, y:Numbe
r):Number{
return x*y;
}

public function division(x:Number, y:Numb
er):Number{
return x/y;

}
public function subtraction(x:Number, y:N
umber):Number{
return x - y; 
}

Operations.mxml

<?xml version = '1.0' encoding = 'ISO-8859-1'?>
<mx:Application xmlns:mx = 'http://www.adobe.com/2006/mxml'>
  
  <mx:Script source = 'includes/IncludedFile.as'/>

    <mx:TextInput id = 'value0' />
    <mx:TextInput id = 'value1'/>

  <mx:HBox>

    <mx:VBox>
      <mx:Label text = 'Addition result'/> 
      <mx:TextArea id = 'result'/>

      <mx:Button label = 'Add' 
click = "result.text = String(addition(Number(value0.text),Numbe
r(value1.text)))"/> 

      <mx:Label text = 'Multiplication result'/> 
      <mx:TextArea id = 'result1'/>
      <mx:Button label = 'Product' 
click = 'result1.text = String(product(Number(value0.text),Numbe
r(value1.text)))'/>
    </mx:VBox>

    <mx:VBox>
      <mx:Label text = 'Division result'/> 
      <mx:TextArea id = 'result2'/>

      <mx:Button label = 'Divide' 
click = 'result2.text = String(division(Number(value0.text),Numb
er(value1.text)))'/>

      <mx:Label text = 'Subtraction result'/> 
      <mx:TextArea id = 'result3'/>
      <mx:Button label = 'Subtract' 
click = 'result3.text = String(subtraction(Number(value0.text),N
umber(value1.text)))'/>
    </mx:VBox>

  </mx:HBox>

</mx:Application>

Operations.swf
16. Action Script 'include' statement example
xample below shows two consequent action script files: GeometricalFigures.as and Sqrt.as,
and the third example, i.e. Figure.mxml is our main flex file inside which the working of 
include statement has been demonstrated. Above mentioned action script files are in the
includes folder that has been called by include statement in the main mxml file. The root
directory of includes folder should match with the root directory and folders of your main
mxml file and ant build file, here it is obvious that your build file and mxml file have same
root directory. Now in the main mxml file, <mx:Script> tags  are made in which two include
statements are used to call two action script files. Action script files posssess .as extension. For
calling the files their relative paths are used. 

Syntax for using include statement:-      

 include '  ';

Action script files can also be called through the source attribute property in <mx:Script> tag,
but in that case only a single action script file will be called. 
Noto : The source property and include statement cannot be used together in <mx:Script>
tags. 

Syntax for using 'source' attribute:-        


<mx:Script source  =  '  '> ...... </mx:Script>

In Our first action script file, GeometricalFigures.as two packages flash.dispaly and mx.core
has been imported for getting the instances of Sprite and UIComponent classes. Further in
the code, two geometrical figures have been created and for creating these figures two Sprite
type variables have been created.  Now graphics feature of Sprite class provides two static
methods: .beginFill() and .drawCircle/Rect(), and among these methods the first one fills
color in the figure and the second one creates the figure. Now our Sprite variables that we
have created are called inside the UIComponent variable through .addChild function, now
the UIComponent variable is called inside the flex Canvas container through the container's 
id  property, which means figures will form inside the Canvas.

GeometricalFigures.as

import flash.display.Sprite;
  import mx.core.UIComponent; 

    public function sqrt():void{
      var num:Number = Number(Math.sqrt(2));
      bn.text = 'Square root of integer "2" is: ' + 
num.toString();
    }

    public var x1:Number = 30;
    public var y1:Number = 40;
    public var z1:Number = 20;
    public var f1:Number = 50;

    public function draw():void{
      var circle:Sprite = new Sprite();
      circle.graphics.beginFill(0xCCFF00);
      circle.graphics.drawCircle(x1,y1,z1);

      var rectangle:Sprite = new Sprite();
      rectangle.graphics.beginFill(0xCFC00);
      rectangle.graphics.drawRect(x1, y1, z1, f1);

      var rose:UIComponent = new UIComponent();
      rose.addChild(rectangle);
      rose.addChild(circle);
      canvas.addChild(rose);

      x1 = x1 + 40;
      y1 = y1 + 5;
      z1 = z1 + 0;
      f1 = f1 + 0
    }

Sqrt.as
public function sqrt():void{
  var num:Number = Number(Math.sqrt(2));
  bn.text = 'Square root of integer "2" is: ' + num.toString();
}

Figures.mxml

<?xml version = '1.0' encoding = 'ISO-8859-1'?>
<mx:Application xmlns:mx = 'http://www.adobe.com/2006/mxml'
               creationComplete = 'sqrt();'>
  <mx:Script>
    include 'includes/GeometricalFigures.as';
    include 'includes/Sqrt.as';
  </mx:Script>

  <mx:Button label = 'click me' click = 'draw()'/>

  <mx:Canvas id = 'canvas' width = '100%' 
        height = '100%' backgroundColor = 'white'>
    <mx:Label id = 'bn' color = 'green' textAlign = 'center'/>
  </mx:Canvas>

</mx:Application>

Figures.swf

   

17. Flex addEventListener example


The example below shows the working of the addEventListener method . As the name
suggests, the method adds events in flex components. Here in the example only mouse event is
added in the components, so whenever a mouse click occurs on the components in which the
events are added, an alert pop up window comes with some messages coded on it. Event
listeners are the methods or functions in which events are added on the flex components or it
can be said as event listeners handles the event that's why they are also called  event handlers.
Here in the example we have two event listener Handler and Handler1 respectively.
With addEventListener method events can be added onto the components indirectly inside
the scripting tags, through the components id attribute or directly by defining in the mxml tag
through click and initialize attributes or properties of the flex components. 

Listener.mxml

<?xml version="1.0" encoding = 'utf-8'?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">

  <mx:Script>
    import mx.controls.Alert;
    
    public function Handler():void{
      b1.addEventListener(MouseEvent.CLICK, alertbox, false, 0); 
    }

    public function Handler1():void{
      t1.text = 'click event disabled ';
      b2.addEventListener(MouseEvent.CLICK, alertbox, true, 0);
    }

    public function alertbox(event:Event):void{
      Alert.show('click event occured');
    }

  </mx:Script> 

    <mx:Button id = 'b1' label = 'b1 control' click = 'Handler()'/>

    <mx:HBox>
      <mx:Button id = 'b2' label = 'b2 control' click = 'Handler1()'/>
      <mx:TextInput id = 't1' editable = 'false'/>
    </mx:HBox>

  <mx:Script>
    
    public function message(event:Event):void{
      Alert.show('welcome to Flex World');
    } 
  
  </mx:Script>
  <mx:HBox>
    <mx:Label text = 'TextInput t2'/>
    <mx:TextInput id = 't2' 
      click = 't2.addEventListener(MouseEvent.CLICK, message, true, 0);'
      editable = 'true'/> 
  </mx:HBox>

  <mx:HBox>
    <mx:Label text = 'TextInput t3'/>
    <mx:TextInput id = 't3' 
      click = 't3.addEventListener(MouseEvent.CLICK, message, false, 0);'
       editable = 'false'/>
  </mx:HBox>

</mx:Application>

Listener.swf

18. Flex Remove Event Listener example


In the example below flex removeEventListener method working is demonstrated. This method
removes the events from the flex components. Here mouse click event are removed by the method. In
the example method doesn't able to remove the event from the button with id b3 because on this flex
control, the associated event is built with the button click attribute.
And this button control tag is under mxml tags, this shows that events cannot be removed that are
added inside the mxml tags. 

removelistener.mxml

<?xml version = '1.0' encoding = 'utf-8'?>
<mx:Application xmlns:mx = 'http://www.adobe.com/2006/mxml'
             initialize = 'addEvent();'>
  <mx:Script>
    import mx.controls.Alert;

    public function addEvent():void{
        b1.addEventListener(MouseEvent.CLICK, alertbox, false, 0); 
    }

    public function removeEvent():void{ 
      b1.removeEventListener(MouseEvent.CLICK, alertbox); 
      b2.removeEventListener(MouseEvent.CLICK, alertbox); 
      b3.removeEventListener(MouseEvent.CLICK, alertbox); 

    }

    public function alertbox(event:Event):void{
      Alert.show('Mouse click event occured');
    }
  
  </mx:Script>

  <mx:HBox>
  
    <mx:Button id = 'b1' label = 'b1 button'/>
    <mx:Button id = 'b2' label = 'b2 button' 
initialize = 'b2.addEventListener(MouseEvent.CLICK, alertbox, false,0);'/>
    <mx:Button id = 'b3' label = 'b3 button' click = 'alertbox(event);'/>
  
  </mx:HBox>

    <mx:TextInput text = 'click to remove click action' 
      click = 'removeEvent()' editable = 'false'/>

</mx:Application>

removelistener.swf

19. Flex dispatchEvent example


The example below demonstrates the working of flex dispatchEvent() method. Method works
like a driver that drives the event mentioned in its constructor. This method is used to manually
dispatch or run away an event. Method, to dispatch any event on the component can be applied
either with the component's id or mouseOver attribute. With mouseOver attribute the method
will be used inside the mxml tags. This means with and inside a control tag attribute,
mouseOver the method can be dispatched on any component. 

Note: With id attribute, method can be accessed through inside as well as outside the mxml
tags. 
Note: mxml tags are the tags used inside the flex application root tag. eg. Flex component tags
like control and container tags.

Syntax for using the method

component's id.dispatchEvent(event_ type, boolean value, boolean value); 

Example for event_type used in the method constructor is MouseEvent.CLICK.


eg:--   b1.dispatchEvent(MouseEvent.CLICK, false ,true);

Inside the method constructor, the first parameter is the event type specified that will be run or
dispatch away by the dispatchEvent method and the second and third parameter are optional
parameters that accept boolean values true and false.

Now in the example below, when the mouse arrow is passed over the component in which the
dispatchEvent  method is invoked,
method dispatches the MouseEvent.CLICK type event on the component. 
With this method, the click based events on components like buttons, check boxes etc can be
manually set to run before the MouseEvent.CLICK i.e. mouse click, actually takes place.

dispatch.mxml

<?xml version = '1.0' encoding = 'utf-8'?>
<mx:Application xmlns:mx = 'http://www.adobe.com/2006/mxml'
                 initialize = 'handler()'>

  <mx:Script>
    
    public function handler():void{
bull.addEventListener(MouseEvent.MOUSE_OVER, dispatcher);
bull.addEventListener(MouseEvent.CLICK, task);
    }

    public function dispatcher(e:Event):void{
  var result:Boolean = bull.dispatchEvent(
    new MouseEvent(MouseEvent.CLICK , false, false));

  }

    public function task(e:Event):void{
      lab1.text += 'Trinity' + '\n';
        txt.text += 'Neo '; 
    }

  </mx:Script>
    
    <mx:Button id = 'bull' label = 'visit over me'/>
    <mx:Label id = 'lab1'/>
    <mx:TextArea id = 'txt' width = '20%' 
          height = '5%' editable = 'false'/>

    <mx:Script>
      import mx.controls.Alert;

      public function handler1(event:Event):void{
Alert.show('Event ' + event.type + ' has been dispatched'); 
      } 

  </mx:Script>
    <mx:CheckBox id = 'ch' label = 'move arrow over me'
      click = 'ch.addEventListener(MouseEvent.CLICK, handler1)' 
      mouseOver = 'ch.dispatchEvent(
      new MouseEvent(MouseEvent.CLICK, true, false))'
      selected = 'true'/>

</mx:Application>

dispatch.swf

20. Flex custom mxml tags example

You might also like