
Beginning ActionScript 2.0 2006
.pdf
Chapter 9
Some things are just quicker and easier to do on the timeline, especially when it involves complex animations.
That said, creating an entire Flash project out of ActionScript is a very powerful approach, and is pretty cool, too!
The method used to attach a component to the stage is createClassObject(), which is a method of the UIObject class. It is defined as follows:
UIObject.createClassObject(className:Object, instanceName:String, ;
depth:Number, [initObject:Object]) : UIObject
Here’s an example:
this.createClassObject(mx.controls.List, “imageList”, this.getNextHighestDepth());
In this example, a List component is placed on the current timeline with default properties set and with the instance name imageList. Once the component instance is on the stage, it can be manipulated with ActionScript in the same way as if it were placed on the stage by hand.
Despite the implication of its name, the className parameter is not a string; it is actually a package reference. A package is a container of classes that are placed within a particular structure to keep them organized and to make sure that if another developer creates a component with the same name, the two component names do not conflict. Think of a package as being like a directory structure. The first directory here is called mx, and within it is another directory called controls, which holds the class definition file for the List component. In fact, that’s exactly how packages are organized. In most operating systems, a single directory cannot hold two files with the same name, but two different files with the same name can co-exist nicely in two different directories. In the same way, a component with the package name com.nathanderksen.ui.List will not conflict with the component mx.controls.List that Macromedia provides.
When working with packaged components, the last portion of the package reference is referred to as the component name, and everything before it is the package name. In mx.controls.List, List is the component name, and mx.controls is the package name.
Using the import statement can save a little space when referring to a packaged class. Once a package has been imported, from that point on you can refer just to the component name and can leave out the package name. The following code shows how the createClassObject() method can now refer just to List, and Flash will automatically associate it with mx.controls.List:
import mx.controls.List;
this.createClassObject(List, “imageList”, this.getNextHighestDepth());
Once a packaged class has been imported, further references to the class can omit the package name, making the code a bit more compact. It is also possible to import a whole set of classes through a wildcard. The following code shows that the wildcard asterisk (*) character has been used with the import statement to import all the classes directly within the mx.controls package. The List component, plus any other components in the same package, can then be referred to without the package name.
import mx.controls.*;
this.createClassObject(List, “imageList”, this.getNextHighestDepth());
238

Working with Components
Only classes that are actually used are compiled into the .swf, and it’s recommended that you import only the classes that you need and refrain from using the wildcard. Having a list of packaged classes at the top of your code tells you what all of your dependencies are, and because avoiding wildcards prevents components that you do not use and may know about from entering your name space, there is less of a chance of two components with the same name entering your name space at the same time and conflicting.
The createClassObject(), which is modeled on the attachMovie() method, enables you to set component properties on creation, as the following example shows:
import mx.controls.List;
this.createClassObject(List, “imageList”, this.getNextHighestDepth(), ; {_x:18, _y:50});
Although that’s convenient, it also makes the code line long enough that you can’t see the properties on the screen without scrolling. Setting the properties on separate lines makes the code a little easier to read:
import mx.controls.List;
this.createClassObject(List, “imageList”, this.getNextHighestDepth());
imageList._x = 18; imageList._y = 50;
You do this in the following Try It Out.
Try It Out |
Placing Components on the Stage with Script |
In this exercise you create the same screen as the preceding Try It Out, but this time you do it all with code. (Don’t worry; you’ll be reusing your precise layout from the previous exercise, so your work won’t go to waste.)
1.Create a new Macromedia Flash document by selecting File New and choosing Flash Document from the New Document panel.
2.Click the first frame in the timeline, open the Actions panel (Window Development Panels Actions), and type in the following ActionScript code:
#include “tryItOut_attachWithScript.as”
3.Open the Components panel (Window Components) and open the User Interface section. Open the library panel (Window Library), and then drag the Label, List, NumericStepper, and ScrollPane components to the middle of the library panel. If you are using Flash MX 2004, drag the four components onto the stage and then delete them from the stage instead.
4.Select File Save As, name the file tryItOut_attachWithScript.fla, choose an appropriate directory, and save it.
5.Create a new Macromedia Flash document by selecting File New and choosing ActionScript File from the New Document panel.
6.Name the file tryItOut_attachWithScript.as and save it in the same directory as the Flash project file.
7.Type the following code into the new ActionScript file:
239

Chapter 9
import mx.controls.List;
import mx.controls.NumericStepper; import mx.controls.Label;
import mx.containers.ScrollPane;
function drawScreen():Void
{
this.createClassObject(Label, “titleLabel”, this.getNextHighestDepth()); titleLabel._x = 18;
titleLabel._y = 18; titleLabel.text = “Image Browser”;
this.createClassObject(List, “imageList”, this.getNextHighestDepth()); imageList.setSize(150, 275);
imageList._x = 18; imageList._y = 75;
this.createClassObject(ScrollPane, “imageViewerPane”, ; this.getNextHighestDepth());
imageViewerPane.setSize(350, 275); imageViewerPane._x = 182; imageViewerPane._y = 75;
this.createClassObject(NumericStepper, “zoomStepper”, ; this.getNextHighestDepth());
zoomStepper._x = 230; zoomStepper._y = 360;
this.createClassObject(Label, “imageListLabel”, ; this.getNextHighestDepth());
imageListLabel._x = 18; imageListLabel._y = 53; imageListLabel.text = “Image List”;
this.createClassObject(Label, “zoomLabel”, this.getNextHighestDepth()); zoomLabel._x = 182;
zoomLabel._y = 361; zoomLabel.text = “Zoom:”;
}
drawScreen();
8.Save the file, return to the Macromedia Flash project file, and select Control Test Movie.
How It Works
Before you can attach components to the stage with script, the components need to be dragged to the library. If the components are not in the library, Flash cannot link them in. This is different from classes where just referring to a class causes the code to be linked in.
Importing the component packages is always the first thing to do in code:
import mx.controls.List;
import mx.controls.NumericStepper;
240

Working with Components
import mx.controls.Label; import mx.containers.ScrollPane;
The drawScreen() function contains the code to place all the components and labels on the screen. First a label is created for the title of the application:
this.createClassObject(Label, “titleLabel”, this.getNextHighestDepth()); titleLabel._x = 18;
titleLabel._y = 18; titleLabel.text = “Image Browser”;
At the moment, it doesn’t look like much, but later in the chapter you apply styles to components, including this label to make it stand out more.
Next, the list box is created, positioned, and sized:
this.createClassObject(List, “imageList”, this.getNextHighestDepth()); imageList.setSize(150, 275);
imageList._x = 18; imageList._y = 75;
Notice that setSize() is used to resize the component. Setting the _width and _height properties do not work the way you expect because everything scales in proportion, including lines and text. setSize() calls the component’s redraw method to make sure that it resizes in the proper way.
The image viewer pane is created:
this.createClassObject(ScrollPane, “imageViewerPane”, ; this.getNextHighestDepth());
imageViewerPane.setSize(350, 275); imageViewerPane._x = 182; imageViewerPane._y = 75;
The zoom stepper is created:
this.createClassObject(NumericStepper, “zoomStepper”, ; this.getNextHighestDepth());
zoomStepper._x = 230; zoomStepper._y = 360;
Finally, two labels are created, and the label values are assigned.
this.createClassObject(Label, “imageListLabel”, this.getNextHighestDepth()); imageListLabel._x = 18;
imageListLabel._y = 53; imageListLabel.text = “Image List”;
this.createClassObject(Label, “zoomLabel”, this.getNextHighestDepth()); zoomLabel._x = 182;
zoomLabel._y = 361; zoomLabel.text = “Zoom:”;
241

Chapter 9
Scripting Components
Each component has a set of methods, properties, and events that are available for you to use. To find out what these are and how to use them, open the Help panel, go to the Components Language Reference section, and open the section for the component in which you’re interested. Figure 9-5 shows an overview of the ComboBox component in the Help panel.
Figure 9-5
In the component documentation you find sections in the overall class definition that mention the methods, properties, and events that are inherited from the UIObject and the UIComponent classes. These two classes are part of the overall component framework, and the methods, properties, and events that they expose are accessible to all version 2.0 components.
The documentation for the NumericStepper class shows that it has some properties with the same name as some of the ones you just saw in the Properties panel, as well as numerous other properties, methods, and events. These are collectively known as an application programming interface (API). To take full advantage of a component, the Properties panel is not enough. You must make use of the component’s API.
To interact with a component, give it an instance name (see Figure 9-6), and then refer to that instance name within the code.
Instance name
Figure 9-6
242

Working with Components
Once an instance name is assigned, the general form for working with the component instance is simple:
instanceName.propertyName = “foo”;
instanceName.methodName();
The code for setting the same properties that were set in the Parameters panel for the preceding Try It Out exercise looks like this:
zoomStepper.maximum = 200; zoomStepper.minimum = 25;
zoomStepper.stepSize = 25; zoomStepper.value = 100;
The following Try It Out extends the first one in this chapter by using code to do the work of the Parameters panel. At this point, for space reasons, we will no longer make use of the example code that places the components onscreen with ActionScript.
Try It Out |
Scripting Components |
In this exercise, you start working with the API for several components.
1.Open the completed tryItOut_scriptingComponents.fla file from the first Try It Out exercise, or open tryItOut_scriptingComponents.fla from the book’s source files at <source file directory>/Chapter 9/tryItOut_scriptingComponents_v1/.
2.Create a new layer on the main timeline; name it Script. Move it so that it is the top layer. Click in the keyframe for the layer, open the Actions panel (Window Actions), and type in the following ActionScript code:
#include “tryItOut_scriptingComponents.as”
3.Save the file.
4.Create a new Macromedia Flash document by selecting File New and choosing ActionScript File from the New Document panel.
5.Name the file tryItOut_scriptingComponents.as and save it in the directory containing the Flash project file.
6.Place the following code into the new ActionScript file:
function init() : Void
{
// Send data to the image list component var imageArray:Array = new Array();
imageArray.push({data:”images/aStudyInTexture.jpg”, label:”A Study In Texture”});
imageArray.push({data:”images/buntzenWinter.jpg”, label:”Buntzen Winter”}); imageArray.push({data:”images/flowerInDetail.jpg”, label:”Flower In Detail”}); imageArray.push({data:”images/galianoSunset.jpg”, label:”Galiano Sunset”}); imageList.dataProvider = imageArray;
// Setup for the progress bar component imageViewerProgress.mode = “manual”;
243

Chapter 9
imageViewerProgress._visible = false;
//Setup for the scrollable image viewer component imageViewerPane.scrollDrag = true;
//Setup for the zoom stepper component zoomStepper.maximum = 400; zoomStepper.minimum = 25; zoomStepper.stepSize = 25; zoomStepper.value = 100;
}
init();
7.Save the file, return to the Macromedia Flash project file, and select Control Test Movie.
How It Works
The exercise begins with initializing the components, giving them startup data, and changing some of their properties. The first few lines of the init() function set up a data provider for the image list component. (A data provider is an array of objects containing properties.) In this case each object contains a data property that provides a unique internal identifier and a label property to show the user. The following code shows the creation of the data provider, with the name of the photo as the label, and the URL as the data for each row:
// Send data to the image list component var imageArray:Array = new Array();
imageArray.push({data:”images/aStudyInTexture.jpg”, label:”A Study In Texture”}); imageArray.push({data:”images/buntzenWinter.jpg”, label:”Buntzen Winter”}); imageArray.push({data:”images/flowerInDetail.jpg”, label:”Flower In Detail”}); imageArray.push({data:”images/galianoSunset.jpg”, label:”Galiano Sunset”}); imageList.dataProvider = imageArray;
The progress bar is set up:
// Setup for the progress bar component imageViewerProgress.mode = “manual”; imageViewerProgress._visible = false;
mode is set to manual, which means that you have to give it a progress value yourself.
The scrollDrag property of the ScrollPane allows the user to grab the image and drag to reposition it:
// Setup for the scrollable image viewer component imageViewerPane.scrollDrag = true;
Finally, the numeric stepper component is given initial parameters (which correspond with the values that you set earlier in the Parameters pane):
// Setup for the zoom stepper component zoomStepper.maximum = 400; zoomStepper.minimum = 25; zoomStepper.stepSize = 25; zoomStepper.value = 100;
244

Working with Components
In the next chapter, you look at coding some user interactions into your components.
Summar y
This chapter explored many different aspects of components. Some points to remember include the following:
Macromedia Flash comes with a variety of components that enable drag-and-drop reusability. Additional components can be added from component repositories such as Macromedia’s Exchange site.
Components can be either placed on the stage manually or added with script. When a component is dragged to the stage, a copy of it is placed in the Library automatically. A component must be manually placed in the Library before it can be added to the stage with script.
Parameters can be set either through the Parameters tab or by setting properties with script.
Each component has an API, a set of properties, methods, and events that can be set or captured with script. You can explore APIs in detail by going to the built-in Help panel and opening the Components Language Reference.
Exercises
1.Create the beginning of a note taker application. Place a DataGrid, two Buttons, three Labels, a TextInput and a TextArea component on the stage with script. Label and arrange them as per Figure 9-7.
Figure 9-7
2.Add code that populates the Notes data grid with some data. It should get three properties from an array of objects: title, size, and text. Only title and size will be shown in the data grid; the other is for data storage purposes. Make the size property a calculated value representing the length of the text string.
245


10
Interacting with the User
The whole point of using Flash to create web applications is to interact with the user. The richness of the interface depends on having a good selection of events that various components can generate. It’s all well if clicking is the only thing that is recognized, but how about mouse-overs, dragging, tabbing, or key presses? These all add to the set of tools for the developer to enhance the user experience.
Most people initially consider only user-generated events such as the ones just mentioned as being important, but there is also the class of system-generated events that occur as a result of either data changes or network communications. You may have asked the server for new data, or perhaps a value changed in response to a user interaction, and that new value needs to be broadcasted to other components. Though you may wonder how this falls under “interacting with the user,” keep in mind that the data generally feeds what the user sees in some way or another. Changes to background data often require updating elements of the user interface.
Handling Events
Any time an event is generated, you need a way to act on that event. When a button is clicked, specific code needs to run. When an entry is selected in a drop-down menu, you need to know that a change has happened, and you need to find out which element is chosen. The code that you write to respond to an event is called an event handler. Event handlers keep you from having to manually query your interface every frame to see if something’s changed. You just assign a block of code to a component, telling it which event to respond to, and the component automatically calls that code every time the event takes place.
Creating a Listener Object
Components use an event handler called a listener. As the name implies, the role of a listener is exclusively to listen for when an event takes place. A listener is an object that is assigned a method for each event for which it will listen. The process of creating a listener is as follows:
1.A custom object is created:
var imageListListener:Object = new Object();