Category: Flex

Populating A TileList On Creation Complete Using XML In Flex

7 November, 2008 | Flex | 1 comment

A TileList is part of a group of elements that allow you to add components in a specific order and orientation. The TileList controls the displaying of a number of items set out as tiles and so it best suited to displaying images as thumbnails.

There are many ways to do this, but none of the examples on the Flex site seemed to be very useful, or very well explained. What I wanted to do was to create a TileList that displayed the tiles in a certain way and used an XML file to fill up the list of items with images, each image having a label associated with it.

The first thing to do is to create the TileList element.

<mx:TileList id="imageTileList" itemRenderer="CustomItemRenderer" dataProvider="{theImages}" width="200" height="400" columnCount="2" creationComplete="initList();"/>

This contains three important attributes, which I have described here.

itemRenderer="CustomItemRenderer"
This attribute is used to tell the TileList how to display each element within the list. The CustomItemRenderer refers to a file called CustomItemRenderer.mxml that contains the following:

<?xml version="1.0" encoding="utf-8"?> <mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" horizontalAlign="center" verticalAlign="middle" verticalGap="0" width="80" height="100" paddingRight="5" paddingLeft="5" paddingTop="5" paddingBottom="5" >   <mx:Image height="50" width="50" source="{data.strThumbnail}" /> <mx:Label height="20" width="75" text="{data.title}" textAlign="center" color="0x000000" fontWeight="normal" /> </mx:VBox>

This tells the TileList that each item should be kept in a VBox element, which contains an Image element to contain the image and a Label element that contains the label for that image. The source and the text attributes for the Image and Label elements respectively are used to tell the elements what data is to go where.

dataProvider="{theImages}"
This is a reference to an ArrayCollection element that provides a mechanism to access the data within the TileList element. This ArrayCollection element looks like the following and needs to be placed as a direct child of the Application element.

<mx:ArrayCollection id="theImages"></mx:ArrayCollection>

creationComplete="initList();&quot
This is an event call that allows us to populate the TileList just after is has been added to the application. The initList() function call is where everything is put together.

The next step is to add a reference to the XML file that contains the information we want to populate the TileList with. Place this as a child of the Application element.

<mx:Model id="items" source="items.xml" />

This references a file called items.xml, which has the following contents.

<?xml version="1.0" encoding="utf-8"?> <items>  <image id="1">     <title>Image 1</title>     <strThumbnail>one.png</strThumbnail>  </image>  <image id="2">     <title>Image 2</title>     <strThumbnail>two.png</strThumbnail>  </image>  <image id="3">     <title>Image 3</title>     <strThumbnail>three.png</strThumbnail>  </image>  <image id="4">     <title>Image 4</title>     <strThumbnail>four.png</strThumbnail>  </image>     </items>

Finally, we are ready to write some code to get this thing working. The first thing we need to do is create a little helper class that will allow us to convert the XML into a usable format. Create a file called ItemListObject.as and put the following contents in it.

package {  [Bindable]  public class ItemListObject extends Object  {   public function ItemListObject() {    super();   }     public var title:String = new String();   public var strThumbnail:String = new String();  } }

Next, you can create your Script element, which contains two main parts. The first is a command that makes the ItemListObject (from the ItemListObject.as) file available to other functions, and the second is the all important call to the initList() function.

<mx:Script>  import ItemListObject;    public function initList():void  {   for each ( var node:Object in items.image ) {    var temp:ItemListObject = new ItemListObject();    temp.strThumbnail = node.strThumbnail;    temp.title = node.title;    theImages.addItem(temp);   }  } </mx:Script>

The initList() function works by getting hold of the items XML file and converting it into an array. For team item it creates a ItemListObject and adds in the Image and Label parts before adding this to the TileList data provider. If everything is working properly then this should produce the following result.

TileList final result

TileList final result

Written by Philip Norton.

External Script Files And Printing Objects With Flex

6 November, 2008 | Flex | No comments

Yesterday I talked about using the Flex Script element to run code within the mxml file, you can also use the source attribute of the Script element to reference external files. To create an external script file FlashDevelop go to the File->New and select Blank Document. You can also do this by pressing Ctrl+N. This will create a blank document that you must save into your src folder of your project with the extension as. Note that if you call this file sourcefile.as then you must reference this in your script tag like this.

<mx:Script source="sourcefile.as">
</mx:Script>

When you do this you will notice that the script file will be part of the Main.mxml file. You can add functions in the same way as you would with an inline script tag.

Printing

With this external script file we will now create some images and print them using the built in printing object that Flex has. This object is called FlexPrintJob and you must include this at the top of your script file if you want to use it. Put the following line at the top of your script file.

import mx.printing.FlexPrintJob;

Create a button in your mxml file that will be used to print.

<mx:Button id="print" label="Print" click="printImage();" />

Add in an image that will be printed.

<mx:Image source="one.png" id="one" />

Here is the image that will be used.

Flex test image

Flex test image

Go back into the script file and add the function that will print the image out. We called this function printImage() in our Button declaration. This function works by creating a new FlexPrintJob object called printJob. This function start() is then used to try and print. Basically, this function returns true if the print job worked, and false if the user clicked cancel.

If the start() function returns true then the object to be printed (in this case the image with the id of "one" is added to the printJob object. Finally, the send() function is called which sends the data off to the printer. Here is the function.

public function printImage():void {  // Create a FlexPrintJob instance.  var printJob:FlexPrintJob = new FlexPrintJob();    // Start the print job and check that it worked  if (printJob.start() != true) {   return;  }    // add object to be printed to the print job  printJob.addObject(one);    // send to printer  printJob.send(); }

This is the simplest use of the FlexPrintJob function as there are controls that can be used to format the pages.

It is possible to print off multiple objects, especially if they are children to another object, by adding the parent object to the FlexPrintJob object. Take the following section of mxml, which defines a Canvas element, with three positioned images as children.

<mx:Canvas id="images">  <mx:Image source="one.png" id="one" x="0" y="0" />  <mx:Image source="two.png" id="two" x="100" y="0" />  <mx:Image source="three.png" id="three" x="0" y="100" /> </mx:Canvas>

This produces the following application.

Three images in a canvas

Three images in a canvas

To print out all three images at once just include the Canvas object instead of the single image object. Change line 11 in the printImage() function from this:

 printJob.addObject(one);

To this.

 printJob.addObject(images);

The printJob object knows about inheritance and will print out everything contained within that element. This includes buttons or any other element that you put into the canvas element.

See the Flex documentation for more information about the FlexPrintJob object.

Written by Philip Norton.

The Script Element, Adding An Action To A Button And Functions In Flex

5 November, 2008 | Flex | 1 comment

Yesterday I talked about creating some simple Flex elements in your application. Today I will introduce a new element called Script.

The Script element, if you haven't already guessed is used to run your application function and should be contained within the Application element. You can either put script inline like this.

<mx:Script> // some code here </mx:Script>

Or you can use the source attribute and link it with an external ActionScript source file.

<mx:Script source="myactionscriptfile.as"> </mx:Script>

The simplest thing you can do is use the function trace(). This is a debugging function that will output information into the debugging Window in your Flex IDE. To print out a message when your application is first run do the following.

<mx:Script> trace('Flex program running.'); </mx:Script>

To capture a mouse click on a Button element you need to use the attribute click, the value of which can be either come code or a callback to a function. To use inline code using the following, which will print out a trace.

<mx:Button id="abutton" label="A button" click="trace('Button clicked');" />

To use a callback function do the following.

<mx:Button id="abutton" label="A button" click="clicked();" />

In your script section you can now add the function that you want, and perhaps do more than just a simple trace() call. The following script will send a trace message to your output and then open a browser window to the #! code site. If you embed this application within a web page then the current browser window will redirect to the URL.

<mx:Script> public function clicked():void {  trace('Button clicked');  navigateToURL(new URLRequest('http://www.hashbangcode.com')); } </mx:Script>

To create a function you need to use the following syntax:

scope function functionName():return type { }

The scope is how the application will see the function. For a function like this that is outside the scope of a class (which is another topic) it should have public scope. The return type is the type of value that is returned by the function, and if no value is to be returned then void is used. If the function adds two numbers together and returns the result then the return type would be Number.

Written by Philip Norton.

Creating Some Simple Flex Interface Elements

4 November, 2008 | Flex | 2 comments

Following on from my previous blog post about installing Flex on Windows I thought I would go through how to create an interface using mxml. When you create a Flex 3 project the first file you are given is called Main.mxml, which has the following content.

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

This file is used to compile and run your Flex project and is the central starting point for all the rest of the compile process. This file controls your interface of your program. At first this file might look daunting, but there are lots of elements to select from and if you know CSS then you should be somewhat familiar with how elements are coloured, padded and positioned.

When you compile your application it will create a swf file in the folder called bin. You can compile and run this file from FlashDevelop, but if you want to just compile it you can navigate to this folder and run the swf file separately.

I will now go through some of the elements that you are likely to need to create a simple interface. It is best to get used to the look and feel of your applications before you get into coding so this post will go over simple interface design and the actual actions will be covered in subsequent posts.

Application

The application element must be the root element of your mxml document. It is basically a container for all the other elements of your application.

Label

The label element is used to add some text to your interface and has the following syntax.

<mx:Label text="A label with some text." />

This will produce the following output.

Label Element

Label Element

Button

The button is exactly what it sounds like, it just adds a button to your interface. The following creates a button called "abutton" with the text "A button", but which has no action.

<mx:Button id="abutton" label="A button" />

This creates the following element.

Button Element

Button Element

Image

Again, the image element is exactly what it sounds like, it adds an image to your application. Here is the syntax.

<mx:Image source="image.jpg" /> This produces the following output with a simple gradient image.
Image Element

Image Element

However, one thing to note is that the source of the image is relative to the path of the swf file in the bin directory. Remember that if you move your swf file you will need to move these files along with it. This took me a while to figure out.

Panel

The panel element is used to contain other elements and create sections in your interface. It is an example of a layout container, which is useful if you want to create a left and right hand panel with different elements in each.

The following example creates a single panel, the full width of the application window, that contains the label, button and image elements that have been previously discussed in this post.

<mx:Panel title="Some example elements" width="100%">  <mx:Label text="A label with some text." />  <mx:Button id="abutton" label="A button" />  <mx:Image source="logo.jpg" /> </mx:Panel>

This produces the following output.

Panell Element

Panell Element

The panel element comes with a fancy set of borders and a header element, if you want to get rid of these then use the following attributes for your panel.

<mx:Panel width="100%" headerHeight="0" highlightAlphas="[0, 0]" borderThicknessTop="0" borderThicknessLeft="0" borderThicknessRight="0" borderThicknessBottom="0" backgroundAlpha="0" dropShadowEnabled="false" cornerRadius="0"> </mx:Panel>

With the addition of the other elements, as in the previous example, this panel now looks like this.

Blank Panel Element

Blank Panel Element

Canvas

The canvas element is like the panel element in that it allows you to add other elements to it and is a layout container. The major difference arises when the elements are rendered. The panel element will stop child elements from overlapping, whereas the canvas element doesn't care and will overlap elements unless you specify x and y coordinates. The following example shows a canvas element that contains a image and a button, both of which are positioned absolutely.

<mx:Canvas width="50%" height="50%" autoLayout="false"> <mx:Image x="0" y="0" source="logo.jpg" /> <mx:Button x="0" y="100" id="abutton" label="A button" /> </mx:Canvas>

This generates the following output.

Canvas Element

Canvas Element

Spacer

The spacer element is used to provide some space between two elements. It is a blank element that should not contain any children and should be used only to add padding between elements. It has the following syntax, in this case the spacer will create a space of 10 pixels in height.

<mx:Spacer height="10" />

There are plenty of other elements to chose from, and this is only a very brief overview of some of the simpler ones. If you want to know more than check out the Flex 3 API Documentation which has more information on all of the elements discussed here, as well as information on many more which can't all be covered here. However, it should be noted that not all of the things discussed on in the API are interface elements. There are things like the Date object which exists simply to provide a wrapper for date functions and form part of your application script, which I will do an introduction to in my next post.

Written by Philip Norton.

Installing Flex 3 On Windows

3 November, 2008 | Flex | 1 comment

Flex is a powerful SDK that allows you to build Flash applications that can then be embedded into any web page. The SDK is that Flex uses quite large and covers a whole range of things from interface controls to data processing. To program in Flex you need to use ActionScript 3. What Flex creates as output is swf files, which can be run separately or embedded into a web page.

To get started you will need the Flex SDK. Download the Flex SDK 3 zip file and extract it into a directory where you can get to it. As an example, I put mine in C:\dev\flex_sdk_3.

Next, you will need something to compile your SDK applications. You could use the Adobe Flex Builder application, but since this is a commercial product it will set you back quite a bit of money. A very good alternative is to use FlashDevelop, which is a free, open source, Flex IDE. I have used it quite extensively and it definitely does the job.

Download FlashDevelop from the site and install it. You will then need to point FlashDevelop to your Flex SDK files. To do this run the IDE and go to Tool->Program Settings, you can also press F10 to get the same menu up. Click on AS3Context in the left hand menu and enter the path to the Flex SDK directory in the Flex SDK Location box. The screenshot below has the dialog box you need open, with the appropriate box filled in.

You will now need to create a new Flex 3 project, which will use the correct Flex SDK to create your application. To do this click on Project in the menu and then click New Project..., which will open a dialog. Scroll down this dialog until you find the section marked ActionScript 3, and select Flex 3 Project. Next, enter a name for your project, define a location and click OK.

Flex create new project

Flex create new project

This will create a directory in the place you stipulated that contains three folders (bin,obj and src) and a file called your_project_name.as3proj. The folder src will contain a file called Main.mxml, which is the name application file that controls everything else.

One final thing you will need is a special version of Flashplayer that will send messages back to your IDE. This is called the Flash debugging version is available from the Adobe website.

You will now need to point FlashDevelop at the debugging version of Flash. Unzip the file that you have downloaded from Adobe (which should be something like sa_flashplayer_9_debug.exe) and place it into a directory that you can get hold of. I put this file into the same folder as before (so as to keep everything in one place). Next open up the options menu again and go to the FlashViewer option in the left menu. Enter the file that you have downloaded.

Flex Flash debug setup

Flex Flash debug setup

So what next? Well I over the next few posts I am going to run through how to create simple applications and also how to solve some common problems that I have encountered whilst using Flex.

Written by Philip Norton.