Tải bản đầy đủ (.pdf) (30 trang)

Flash CS4 Professional in 24 Hours- P12 pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (534.44 KB, 30 trang )

ptg
Using the RadioButton Component
321
Unlike the Button components you created in the previous task, each of
your RadioButton component instances changes to reflect its current label.
That is, you can see the labels Novice, Intermediate, and Expert without
even testing the movie. This feature is called Live Preview, and it shows the
benefit of populating a Component’s label property with the Parameters
panel over populating it in the ActionScript code, as you did in the previ-
ous task.
Apply the Radio
Buttons
TRY IT YOURSELF

Although your radio buttons are nice, they don’t really do anything. Follow
these steps to give the buttons some practical use:
1. Using the movie from the preceding task, drag a Button component
onto the Stage. Use the Component Inspector to set this button’s la-
bel to
Continue. Give the Button component the instance name
continueButton.
2. Make sure the button is on the Stage in Frame 1 with the three in-
stances of radio buttons. Go to Frame 2, and insert a blank keyframe
by pressing F7. On the screen, you create the content for the Novice.
Put some text onscreen that says ‘Welcome novice’. Insert a blank
keyframe on Frame 3, and draw the content for the Intermediate user.
Finally, on Frame 4, insert a blank keyframe, and draw some content
for the Expert. Go back to Frame 1 to set up the code for the user to
interact with these buttons.
3. Click Frame 1, and open the Actions panel. Type this code in it:
stop()


continueButton.enabled = false
noviceButton.addEventListener(MouseEvent.CLICK, revealContinue )
intermediateButton.addEventListener(MouseEvent.CLICK, revealCon-
tinue )
expertButton.addEventListener(MouseEvent.CLICK, revealContinue )
function revealContinue ( evt ) {
continueButton.enabled = true
}
continueButton.addEventListener(MouseEvent.CLICK, clickContinue )
function clickContinue ( evt ){
var frameNumber = 1 + Number( noviceButton.group.selectedData )
gotoAndStop ( frameNumber )
}
From the Library of Lee Bogdanoff
ptg
322
HOUR 17: Introducing Components
It would be nice if components required even less scripting than they do.
Even this simple example took a bit of work. The previous tasks on the
ComboBox, Button, and RadioButton gave you a solid foundation on the
basics. Next hour, you get to create more complete examples and explore
other components. Before then, in the rest of this hour, you learn ways to
change the component’s appearance.
Changing Component Appearances
Components include code and graphics. However, you can change both the
style of various elements, such as the font for the labels, as well as any of
the graphics, called skins, contained in the component. For example, you
could use italic text for the label on a button. Or modify the Button, so it is
circular. In fact, you can change even more attributes, such as the way the
ComboBox opens and closes, but this section concentrates only on control-

ling how the components look.
We cover two approaches here: First, you see how to manually edit a com-
ponent’s skin. Second, you see how you can use ActionScript to change any
style element in the component, including text layout and skins.
TRY IT YOURSELF

Apply the Radio
Buttons
There’s an interesting approach here. The first line stops the Timeline
from continuing past the buttons in Frame 1. The second line of code
sets the enabled property on the
continueButton instance to false
so the user can’t click it yet. All three RadioButtons broadcast their
CLICK to the homemade function
revealContinue. That function
does nothing except enable the
continueButton instance. The
continueButton broadcasts its CLICK event to the homemade func-
tion
clickContinue. It is inside that function that we first calculate
the frame number by adding 1 to the
selectedData property of the
group to which the
noviceButton is a part. It’s definitely weird that
we’re using just the
noviceButton instance, but notice we’re grabbing
the
selectedData (that’s the data parameter from whichever button
in the group is currently selected). Because all the RadioButton in-
stances are part of the same group, it doesn’t matter which button we

use.
4. Test your movie.
From the Library of Lee Bogdanoff
ptg
Changing Component Appearances
323
Manually Editing Component Skins
If you want to change the appearance of any component, simply double-
click an instance onstage, and you are faced with all the editable elements.
For example, Figure 17.6 shows the contents of a Button component.
It’s almost too easy. For example, if you want to change the Up state for the
Button component, just double-click the rectangle to the left of the word
Up, and you are taken inside the Button_upSkin symbol, where you can
edit the graphics.
To start, we recommend editing only the colors, such as the button’s fill. If
you decide to edit the shape of a Component, you want to be sure each
state is the same size so the outlines match. Otherwise, your users might ex-
perience a blinking effect like a cat chasing its tail. They roll over the Up
state; then, when faced with the Over state that’s not the same shape, the
cursor might not be over the button, so it reverts to the Up state, and the
blinking repeats.
Components take advantage of a powerful feature called 9-slice scaling. The
feature enables you to scale components to any shape without distorting
the corners. In Figure 17.7, you can see the Button component scaled to var-
ious shapes, along with a mocked-up version of how they’d look without
the 9-slice feature.
FIGURE 17.6
You can manually edit any or all of
the Button component’s 10 states.
From the Library of Lee Bogdanoff

ptg
324
HOUR 17: Introducing Components
The reason we mentioned 9-slice scaling is because you see the nine slices
when editing the skins, such as the Button_upSkin shown in Figure 17.8.
Probably the best advice is don’t move those guides. Otherwise the graph-
ics in the corners never stretch, the graphics in the center always stretch,
and then the middle sides and middle tops stretch only when the compo-
nent is scaled taller or wider, respectively.
Setting the Style of a Single Component
Instance
Although editing the visual elements inside a component is fairly intuitive,
there are a couple of reasons why you might want to change its look with
ActionScript. The big reason is you want to modify the text formatting, like
for the label on a button. Other reasons are that you want to change a visual
With 9-slice scaling Without 9-slice scaling
FIGURE 17.7
Without 9-slice scaling (shown on
the right), the Button component
would look inconsistent whenever
you scaled it.
Stretches as
component
grows taller
Never stretches
Never stretches
Never stretches
Never stretches
Stretches as component grows wider
Stretches anytime

component scales
Stretches as component
grows wider
Stretches as
component
grows taller
FIGURE 17.8
The 9-slice scaling guidelines are
shown when the skins are being
edited.
From the Library of Lee Bogdanoff
ptg
Changing Component Appearances
325
element in one instance of a component or in one class of component, like
all the Button instances. The mechanism to change visual styles using Ac-
tionScript is through the methods
setStyle() and setComponentStyle().
The only catch is the way you do it is different when affecting one instance,
one component class, or all components in your movie. We start with affect-
ing just one instance. The form is
myInstance.setStyle(‘theStyle’, value);
You have to replace myInstance with the instance name of your compo-
nent, replace
theStyle with the supported style found in the Help files, and
replace
value with an actual value. It turns out the most common style you’
are changing is the
textFormat. However, when you set the textFormat
style, you must set it equal to a TextFormat object. That is, you first create a

TextFormat instance, modify it (such as by setting the font and size), and
then use it in place of the value when calling
setStyle(). Here’s an exam-
ple that changes the font used for a RadioButton instance named
myRB:
var myFormat = new TextFormat()
myFormat.color = 0x00FF00
myFormat.size = 20
myRB.setStyle(‘textFormat’, myFormat)
Notice the first three lines involve creating and customizing the myFormat
variable, and then in the last line, the style is finally applied to the myRB
instance.
Setting the Style of One Component Type
You can affect all instances of a particular component class by using this
complex code:
import fl.managers.StyleManager
import fl.controls.Button
var myFormat = new TextFormat()
myFormat.color = 0x00FF00
myFormat.size = 20
StyleManager.setComponentStyle(Button, ‘textFormat’, myFormat)
The first two lines are necessary to use the StyleManager and to reference
the Button component class. The next three lines fashion the
TextFormat in-
stance (
myFormat). Finally, the last line triggers the setComponentStyle()
method, which is similar to setStyle(), but includes the component class
you want to affect (in this case, Button).
From the Library of Lee Bogdanoff
ptg

326
HOUR 17: Introducing Components
Setting the Style of All Components
Finally, you can affect a style for all instances of all components with the
following code:
import fl.managers.StyleManager
var myFormat = new TextFormat()
myFormat.color = 0x00FF00
myFormat.size = 20
StyleManager.setStyle( ‘textFormat’, myFormat)
This code is nearly identical to what you would use to set the style for a
component class, except we’re using the
StyleManager’s setStyle()
method instead of setComponentStyle().
Summary
Components have grown up since their ancestors first appeared in Flash 5
as Smart Clips. Components help bridge the separation between program-
mer and nonprogrammer. This hour you have learned how to populate
components manually by using the Component Inspector, as well as how to
populate components by using ActionScript. In addition, you have learned
how to use
addEventListener to make components trigger your own cus-
tom code.
This hour you have seen details of the ComboBox, Button, and RadioButton
components. You see many more components next hour. This hour you
have also learned the basic scripts for changing the styles of components.
Q&A
Q. Is there a benefit to using components instead of doing everything
from scratch?
A. Definitely. The main benefit is components offer a quick way to build an

application with ready-made and quite complex pieces that alleviate you
from having to make a customized version each time. For example,
we’ve probably built homemade scrollbars in more than 50 projects.
Each time we had to do it from scratch. Although the components are
customizable (both as far as the content they display and the visual
skins), sometimes you do need to build things from scratch.
From the Library of Lee Bogdanoff
ptg
327
Summary
Q. If components are supposed to make things so easy, why was there so
much ActionScript this hour?
A. You can populate many attributes of your components via the Parame-
ters panel. However, you do need ActionScript to make the components
do anything. Consider if you could do everything via the Parameters
panel—that would mean a lot of clicking around. With a little bit of Ac-
tionScript, you can make the components do some powerful stuff. The
point is components are designed to require the absolute minimum
code from you.
Q.
I’m beginning to like components, but I see there are more than just
the ComboBox, Button, and RadioButton. How do I learn to use those?
A. First, the basics covered this hour should give you enough to get you
started with all the components. They’re very consistent. The idea with
this hour is to concentrate on the consistencies, and then next hour, we
explore applications that use additional components.
Q.
I liked how I was able to change the skin on the Button component, but
I want to change the skin on just one instance. When I make a change,
it affects all Button instances onstage. What if I want one button to be

tinted red? Is that possible?
A. There are actually a few ways to do that. First, see whether you can use
the Tint option in the Properties panel’s Color drop-down if you’re chang-
ing only the color. (Note you don’t see the effect until you test the
movie.) That’s not quite the same as going into and editing the skin for
the button. To create an alternative skin for one instance, find the Movie
Clip symbol in the Library for that skin. For example, inside Component
Assets is a folder called Button Skins; inside that is a symbol
Button_upSkin. Right-click on that symbol, and duplicate it. Call it But-
ton_upSkin_MINE, and before you click OK, use the advanced part of
the Duplicate Symbol dialog (expand it if it’s not visible). Click the option
Export for ActionScript. (It also checks the Export in the first frame you
want selected.) Ensure the Class field reads Button_upSkin_ MINE.
Click OK, and then edit the symbol’s contents. When you’re finished,
you can replace the upSkin style for any Button instance by using this
code:
myInstance.setStyle(‘upSkin’, Button_upSkin_MINE)
From the Library of Lee Bogdanoff
ptg
328
HOUR 17: Introducing Components
Workshop
The Workshop consists of quiz questions and answers to help you solidify
your understanding of the material covered in this hour. You should try to
answer the questions before checking the answers.
Quiz
1. The Button component is identical to the homemade Simple Buttons
because they both only have states for Up, Over, Down, and Hit.
A. True.
B. False. Simple Buttons have several other states.

C. False. The Button component has several other states.
2. What happens if you try to scale a component to make it wider?
A. It works, but the text gets distorted.
B. It works, but the shape might appear distorted.
C. It works; thanks to the 9-slice scaling feature.
3. You should use radio buttons only when providing the user with a selec-
tion of audio tracks.
A. True. Why do you think they’re called radio buttons?
B. False. Radio buttons can be used for any purpose you want.
C. False. Radio buttons should be used only for mutually exclusive
choices.
Quiz Answers
1. C. The Button component has states for Up, Down, and Over—plus
selected versions of those three, plus a disabled state, and two out-
lines (one for when the button has focus and one for when you want
to emphasize the button). Simple buttons have Up, Over, Down, and
the Hit state discussed in Hour 16.
2. C. It’s sort of magic really. Note you can’t successfully rotate or skew
a component.
3. C. Radio buttons should be used only for mutually exclusive choices,
such as male and female. Check box-type buttons are for situations in
which multiple selections are possible, such as when choosing pizza
toppings like pepperoni, olives, and sausage.
From the Library of Lee Bogdanoff
ptg
WHAT YOU’LL LEARN IN
THIS HOUR:
. How to use data
providers to populate
list-based components

(ComboBox, List, and
DataGrid)
. How to use additional
user interface compo-
nents
. How to integrate multi-
ple components into
practical applications
Last hour you learned the basics of using components. Not only did you
learn how to populate them with data, both manually and with Action-
Script, but you also saw how to write ActionScript to respond to events
such as the user clicking a button. You learned how to change the compo-
nents’ visual appearance. In fact, you learned the core foundation of using
components. In this hour, you go beyond that to learn how to use addi-
tional components and, more importantly, how to integrate multiple com-
ponents into practical uses.
Using Data Providers
Because you’ve already seen how to populate components and set up event
listeners to make components broadcast events to your code, there’s not
that much more to learn. However, one concept worth learning in more
depth is how the data that populates your component is structured. In the
case of a Button, there’s not much more than the
label property the user
sees on the button. However, with list-based components, such as ComboBox,
List, DataGrid, and TileList, each item in the list can store additional data.
You might remember when you populated the ComboBox, there was a list
of items, each of which had both a label and a piece of data. Users saw the
list of all the labels by clicking the ComboBox, and when they selected one
of the items, your code grabbed the data in that slot. This list of label/data
pairs is called the component’s data provider. Three basic approaches to pop-

ulating such components include manually entering the values via the
Component Inspector panel, using the
addItem() method to populate with
ActionScript, or creating a data provider (a variable) that you associate with
the component.
HOUR 18
Using Components
From the Library of Lee Bogdanoff
ptg
330
HOUR 18: Using Components
Entering values manually through the Component Inspector panel is fairly
intuitive. As you recall from last hour, you selected a ComboBox instance
and clicked the
dataProvider property in the Component Inspector panel
to reveal the values dialog, where you could add as a many label or data
pairs as you wanted, as shown in Figure 18.1.
The main disadvantage to populating components in this manual manner
is it involves a lot of clicking around. For example, if you want to inspect
the current values, you have to return to the Component Inspector panel. A
more significant disadvantage is you can’t make changes to the ComboBox’s
contents while the movie plays.
Using ActionScript to populate a component improves on some of the is-
sues with using the Component Inspector. For example, you can use
addItem() to populate the component. Consider this code, which populates
a ComboBox instance named
myCombo:
myCombo.addItem( { label: “Microsoft”, data: “” }
)
myCombo.addItem( { label: “Adobe”, data: “” } )

This code has exactly the same outcome as populating manually with the
Component Inspector panel. As a reminder, you can ascertain the data
value for the currently selected item with this expression:
myCombo.selectedItem.data
FIGURE 18.1
The Component Inspector panel en-
ables you to enter labels and data
values into the ComboBox compo-
nent.
From the Library of Lee Bogdanoff
ptg
Using Data Providers
331
For example, last hour we used the following code to take the user to the
URL stored as the
Value property in the currently selected item:
var myURL = new URLRequest( myCombo.selectedItem.data );
navigateToURL( myURL );
It’s important to understand the way the addItem() method works. You
pass a single parameter in the form of an ActionScript object. Literal Action-
Script objects look like this:
{property: “value”, property2: “value2”}
The property names are arbitrary, but they can’t start with a number or in-
clude spaces, and they’re always shown without quotes. The values can be
any data type. Here they’re shown as strings. As in the case of the Action-
Script object used as the item for a ComboBox in the
addItem() method,
they traditionally include a
label property and a data property. This
matches the exact structure shown earlier in Figure 18.1.

In this example, populating the ComboBox with the
addItem()method has
the advantage that you can see all the values without clicking the Compo-
nent Inspector panel. However, another big advantage is that you’re not
limited to storing only two bits of information in each item. So far, each
item has only a
label and a data property, but you could add as many ad-
ditional properties as you’d like to suit the content. You always want the
label property, but you can add additional pieces of data property. For ex-
ample, say you’re listing a bunch of dogs and want to include their age and
gender. Check out this variation:
myCombo.addItem( { label: “Rover”, age: 2, gender: “m” } )
myCombo.addItem( { label: “Max”, age: 3, gender: “m” } )
myCombo.addItem( { label: “Puffy”, age: 1, gender: “f” } )
Because the label properties are expected by the component, you see the three
dog names as expected. It gets cool when you need to grab a value from the
ComboBox. Check out the following code that traces the name, age, and gen-
der when the user changes the
myCombo instance. You can try it yourself by cre-
ating a ComboBox onstage with the instance name
myCombo and the preceding
three lines of code plus the following code in the Action panel for Frame 1:
myCombo.addEventListener( Event.CHANGE , changeCombo)
function changeCombo( evt ) {
trace(“the name is “ + myCombo.selectedItem.label )
trace(“the age is “ + myCombo.selectedItem.age )
trace(“the gender is “ + myCombo.selectedItem.gender )
}
From the Library of Lee Bogdanoff
ptg

332
HOUR 18: Using Components
You build some more practical applications in the tasks that appear later
this hour. You can grab any item’s properties by name by referring to the in-
stance’s
selectedItem property. In fact, you can grab any item by index
(that is, which row it’s in) by using
getItemAt(). For example:
trace(“the first dog’s age is “ + myCombo.getItemAt(0).age )
Now you’ve seen two ways to populate a component’s data provider: The
Component Inspector panel and using the
addItem() method. The advan-
tages of
addItem() are that you can see all the content in one place, and you
can add additional arbitrary properties to fit your content. The last thing to
see is how to create a separate data provider variable that holds all the con-
tent and then associate that variable with your component instance. This
enables you to maintain the data separate from any one component in-
stance. If the data changes, the component updates. Plus, you can associate
one data provider with multiple components. It’s a nice way to separate the
data from a specific component instance.
The code for populating a data provider is almost identical to that for pop-
ulating a component’s items. That is, you use
addItem(). However, you
need to add an extra step at the beginning to create your data provider in-
stance. (There’s no instance onstage like with components.) You also add
one step at the end to associate the data provider with your component.
Here’s an example:
import fl.data.DataProvider;
//create a data provider

var myDataProvider:DataProvider = new DataProvider();
//populate it
myDataProvider.addItem( { label: “Rover”, age: 2, gender: “m” } )
myDataProvider.addItem( { label: “Max”, age: 3, gender: “m” } )
myDataProvider.addItem( { label: “Puffy”, age: 1, gender: “f” } )
//associate the myDataProvider instance with the component on stage:
myCombo.dataProvider = myDataProvider;
You need the import statement first so Flash knows what DataProvider is.
In the end, there’s no effective difference between this code and the previ-
ous examples. The difference is you can associate
myDataProvider with
other components because it is a separate variable. In addition, if you mod-
ify the
myDataProvider instance (say, you update the age property in one of
the items, or you completely remove an item), all the associated compo-
nents update to reflect the new values. For example, you might have a fea-
ture where you enable the user to add items to a list.
CAUTION
0-Based Indexing
The first item in any list is in the
0 index. For example,
myCombo.
getItem(0)
returns the first
item in the
myCombo instance.
Remember it starts counting
with 0, not 1.
From the Library of Lee Bogdanoff
ptg

Using Data Providers
333
Although the ComboBox is great when it’s needed, realize all the informa-
tion in this section also applies to the other list-based components, as you
explore in the following tasks. As a quick summary, list-based components
enable you to store multiple items, although only the
label properties are
visible. By using
addItem() on the component or its data provider, you can
add additional arbitrary properties.
Using the List Component
After the preceding overview of data providers, it’s about time to build
some applications with the components. We start with the List. The only
difference with the List and the ComboBox is the List doesn’t expand and
collapse. It’s appropriate for times when the user might need to quickly
scan all or most of the items in a list. The ComboBox is appropriate when
the user needs to access the items, but most of the time you want the list
hidden and only the currently selected item visible. Plus, it’s possible to
make multiple selections with the List component.
We do a quick exercise with just the List component. The main work is in
the functional design and the ActionScript.
Use the List Compo-
nent to Enable Users
to Select Images
TRY IT YOURSELF

This task might look a little familiar, but it’s still useful. Follow these
steps:
1. Create a new Flash File (ActionScript 3.0). From the Components
panel, drag a List component onto the Stage. Use the Parameters

panel to give it an instance name
myList.
2. Use the Text tool, and click to create a block of text wide enough to
serve as a photo caption. Use the Properties panel to set the text to
Dynamic Text, and give it an instance name
myText.
3. Use the Rectangle tool to draw a square to hold the photos, which,
for now, are temporary graphics we draw. Select the drawn rectangle,
and convert it to a Movie Clip symbol called Content (select Modify,
Convert to Symbol, ensure the behavior is Movie Clip, and click OK).
Use the Properties panel to give the instance of the Content symbol
onstage the instance name myContent.
4. Double-click the
myContent instance to edit its contents. Click Frame
5, and insert a frame by pressing F5. This layer is the background. In-
sert a new layer by choosing Insert, Timeline, Layer, and make each
frame a keyframe. Into each frame, either import a small photograph or
quickly draw a temporary graphic, such as a rough 1, 2, 3, and so on.
From the Library of Lee Bogdanoff
ptg
334
HOUR 18: Using Components
Feel free to modify the three lines starting myData.addItem with content
that matches your photos. Most of this code should look familiar. It’s a bit
ugly at the very bottom under
//initialize, where the content and list is
made to appear as though the user already clicked the first item. Initially,
the user sees everything configured as if they already selected the first item
in the list. Notice in the second to the last line of code, we’re not jumping to
Frame 1, but rather to the frame number matching the frame property of

the item in the 0 index of the data. It’s arguable whether this additional
TRY IT YOURSELF

Use the List Compo-
nent to Enable Users
to Select Images
5. Return to the main Timeline. Your layout should look like Figure 18.2.
myList instance of
List component
myContent instance
Content Movie Clip
myText instance of Dynamic Text
FIGURE 18.2
This layout has a List compo-
nent, a clip full of photos, and a
text field for the captions.
6. Click the first keyframe, and open the Actions panel. Type the follow-
ing code:
//make the data:
import fl.data.DataProvider;
var myData:DataProvider = new DataProvider();
myData.addItem( {label:”Sunset”, frame:1, caption:”This is a sun-
set” } )
myData.addItem( {label:”Sunrise”, frame:2, caption:”This is a sun-
rise” } )
myData.addItem( {label:”Beach”, frame:3, caption:”This is the
beach” } )
//associate the data
myList.dataProvider = myData;
//set up the listener:

myList.addEventListener( Event.CHANGE , changeList )
function changeList ( evt ){
//display the photo:
myContent.gotoAndStop ( myList.selectedItem.frame )
//show the caption:
myText.text = myList.selectedItem.caption
}
//initialize:
myText.text = myData.getItemAt(0).caption
myContent.gotoAndStop (myData.getItemAt(0).frame )
myList.selectedIndex = 0
From the Library of Lee Bogdanoff
ptg
Using Data Providers
335
complexity is worthwhile. A decent alternative would be to always place
the photo for the first item in Frame 1, but this way you can change the
structure if you want.
Using the DataGrid Component
The DataGrid component is like the List component, except instead of
many rows of data, you can have multiple columns, too. One nice feature
for users is they can sort the items in the DataGrid component by clicking
the column headers. For example, with a list of sports team’s statistics, the
user could sort by team name or score, as shown in Figure 18.3.
FIGURE 18.3
Users can interact with the data by
clicking a column to sort the list.
Using the DataGrid in the most basic way, you make a DataProvider and as-
sociate it with the DataGrid (or populate manually using
addItem() on the

DataGrid instance). A basic example is expanded in a minute. Place a Data-
Grid instance onstage, and give it the instance name
myDG. Put this code in
the first keyframe:
import fl.data.DataProvider;
var myData:DataProvider = new DataProvider();
myData.addItem({team: “Dallas”, wins:67 , losses:15 , percent:0.817 } )
myData.addItem({team: “Phoenix”, wins:61 , losses:21 , percent:0.744 } )
myDG.dataProvider = myData;
You can insert additional rows by using addItem(). You don’t need a label
property. Also, whatever names you give the items’ properties appear as
column headers. Even with just this code, the DataGrid component is use-
ful. There are a few touchups that we’re going to show you because you’ll
probably encounter them in your future work. It’s worth warning you,
however, you can stop here and still use the DataGrid component quite ef-
fectively. The ActionScript that appears in the rest of this section doesn’t
From the Library of Lee Bogdanoff
ptg
336
HOUR 18: Using Components
come with full explanation. We include it here because these are common
tasks you want to do with the DataGrid component.
First, to change the order of the columns, you need to access the
columns
property of your DataGrid instance (myDG in the earlier example). For exam-
ple, to place the team names first, you would add the following line of code:
myDG.columns = [“team”, “wins”, “losses”, “percent”]
You can do quite a lot more with columns, and there’s an entire class called
DataGridColumn. This code works as is.
Another thing you might want to do is show only a portion of the data. Re-

member how the List component always hides the data values from the
user? You might need something similar with a DataGrid. For example,
maybe you want to store the URL for each team in the DataProvider, but
not necessarily show the users those URLs right inside the DataGrid. To see
this effect, you could use the following line of code to hide the percentages:
myDG.columns = [ “team”, “wins”, “losses” ]
Another thing you might want to do is to change the actual wording that
appears in the column header. Property names in your items (such as
team,
wins, losses, percent) can’t include spaces. If you want the first column to
appear as
Team Name, you’d need to add this code:
myDG.columns[0].headerText = “Team Name”
Notice before where the entire columns property is being overwritten and
set to an array of three or four names, here the
headerText property is be-
ing set for the column in the 0 index as
columns[0] grabs the first column.
This code is getting a bit tangled, and there’s no room to fully explain it. It’s
a good initial step into some advanced and particularly useful maneuvers
that you want to do with the DataGrid component.
There’s one thing that’s especially difficult, but it does hint at some addi-
tional powerful tricks you can try. Imagine you’d like the percentages to ap-
pear in a more traditional manner—for example, as
80% instead of 0.80.
Doing so is slightly complex, as you see. The key concept to understand is
your raw data can be kept separate from the way it gets displayed. That is,
the DataProvider can maintain the 0.80 number (in case you need to do some
math with that number), but you can write code that reformats that number
into something that’s more digestible for the user to see in the display

(namely, 80%). That’s the concept behind a column’s
labelFunction prop-
erty as well as the even more advanced topic of cell renderers—which we
From the Library of Lee Bogdanoff
ptg
Working with Other Components
337
only mention as a way to replace cells in your DataGrid with icons or other
graphics. Here’s some code that reformats the percent column’s display:
myDG.columns[3].labelFunction = formatPercent;
function formatPercent ( item ) {
return Math.round(item.percent*100)+”%”
}
This code works only if your fourth column still displays the percent property.
Working with Other Components
There’s not a whole lot more we can say about components. At this point,
you should learn by using them, so that’s what you do for the rest of this
hour. First, you use the ProgressBar component to build a loading bar that
shows users how much of your movie has loaded. Second, you use the
Slider component to enable users to set a value within a set range.
Using the ProgressBar Component
The ProgressBar component can be used in two general ways, as shown in
Figure 18.4. Either it can fill up like a thermometer to give the user a visual
clue how a process is progressing, or when the duration of a procedure
can’t be figured out by your code, the ProgressBar can display a “barber
pole” graphic.
Your initial approach to using the ProgressBar might be more complex
than it needs to be. For example, to set the mode to Manual, you could use
this line:
myProgressBar.mode = “manual”

Then periodically trigger the setProgress() method, like this:
myProgressBar.setProgress ( 50, 100 )
This code would display a half-filled progress bar.
However, this component is more sophisticated than that. With one line of
code, you can make a ProgressBar display the percentage loaded in your
movie or anything else you load into your movie such as audio or video.
Here’s the code:
myProgressBar.source = this.loaderInfo
Let’s do a quick task, so you have something useful.
FIGURE 18.4
The ProgressBar can display how a
process is progressing (top) or dis-
play the barber pole animation (bot-
tom) when the duration is
indeterminate.
From the Library of Lee Bogdanoff
ptg
338
HOUR 18: Using Components
TRY IT YOURSELF

Use the ProgressBar
Component as a
Preloader
Although only one line of code makes the progress bar, a few more steps
gets everything working in a useful way.
1. Create a new Flash File (ActionScript 3.0). Drag a ProgressBar compo-
nent onto the Stage. You can optionally resize or scale it to fit your
needs. Use the Properties panel to give the ProgressBar instance the
name

myProgressBar.
2. To make your movie larger (that is, to make it load slow enough to
need a progress bar), click Frame 2, and insert a blank keyframe by
choosing Insert, Timeline, Blank Keyframe (or press F7). Import a
large image, and place it onstage in Frame 2. Alternatively, you could
import some music—make sure to make it start playing on Frame 2.
3. Go back to Frame 1, click the keyframe, open the Actions panel, and
begin with these two lines of code:
stop()
myProgressBar.source = this.loaderInfo
The stop() ensures you don’t go straight to Frame 2. (You want to
show users the
ProgressBar component first.) The second line sets
the source property of the
myProgressBar instance equal to the load-
erInfo of the main Timeline. The
loaderInfo property contains all the
information the
ProgressBar component needs to display the bar.
4. You’re not done yet, but go ahead and select Control, Test Movie. The
progress bar should appear fully filled because the file downloads in-
stantly when you’re running it on your hard drive. While you’re still
testing the movie, select View, Simulate Download to see how it
might appear after you post it on the Internet. Although the
ProgressBar component fills up nicely, the next thing to add is some
code to make it advance to Frame 2 after your file is fully loaded.
5. Return to your Flash file, and add the following code to the code you
already have in Frame 1:
this.loaderInfo.addEventListener( Event.COMPLETE, loadComplete )
function loadComplete( evt ){

gotoAndStop(2)
}
The first line uses addEventListener() to broadcast the COMPLETE
event to the homemade function
loadComplete(). From there, you
simply advance to Frame 2. If your movie has an animation that starts
on Frame 2, you can change
gotoAndStop(2) to gotoAndPlay(2) in-
stead.
From the Library of Lee Bogdanoff
ptg
Working with Other Components
339
Using the Slider Component
The Slider component is a handy way for users to visually set a value that
stays within a range you establish. Perhaps you want to allow users to fill in
a satisfaction survey that ranges from 10 for extremely satisfied to 0 for ex-
tremely dissatisfied, as shown in Figure 18.5. Or, maybe you want to allow
them to set the speed at which your slideshow advances. The fact the Slider
component is visual makes it more appropriate for certain conditions.
FIGURE 18.5
The slider component gives users a
visual way to set values that stay
within a range you establish.
Using the Slider component is fairly easy. Usually all you need to do is set
the minimum and maximum, and then set up a listener for when the Slider
changes. Grab the slider’s current value and do what you want with it (save
it in a survey, change the speed of your slideshow, and so on).
Here’s a simple task that enables the user to jump to any frame in a Movie
Clip.

Use the Slider to
Access Frames
in a Movie Clip
TRY IT YOURSELF

To keep things simple, you’ll create a Movie Clip with different content on
each frame, as we’ve done previously.
1. Create a new Flash File (ActionScript 3.0). From the Components
panel, drag a Slider component onto the Stage. Use the Parameters
panel to give it an instance name
mySlider. You can resize or scale
the slider if you’d like.
2. Use the Rectangle tool to draw a square to hold some content, which
are temporary graphics you draw. Select the rectangle, and convert it
to a Movie Clip symbol called Content (select Modify, Convert to
Symbol, ensure the behavior is Movie Clip, and click OK). Use the
Properties panel to give the instance of the Content symbol onstage
the instance name
myContent.
From the Library of Lee Bogdanoff
ptg
340
HOUR 18: Using Components
TRY IT YOURSELF

Use the Slider to
Access Frames
in a Movie Clip
3. Double-click the myContent instance to edit its contents. Click Frame
5, and insert a frame by pressing F5. This layer is the background. In-

sert a new layer by choosing Insert, Timeline, Layer, and make each
frame a keyframe. Into each frame, either import a small photograph,
or quickly draw a temporary graphic, such as a rough 1, 2, 3, and so
on.
4. Return to the main Timeline, select the first frame, and open the
Actions panel. Then, type this code:
import fl.events.SliderEvent
myContent.stop();
mySlider.minimum = 1;
mySlider.maximum = myContent.totalFrames;
mySlider.addEventListener(SliderEvent.CHANGE, changeSlider);
function changeSlider (evt){
myContent.gotoAndStop(mySlider.value);
}
The second line stops the myContent clip from playing initially. Next,
you set the minimum and maximum properties of the
mySlider in-
stance. Notice instead of the maximum being set to a hardwired 5, it
is set to match the
totalFrames property of the myContent Movie
Clip. This way, if you add frames to the Movie Clip, the code still works
correctly. Finally, the
addEventListener() is used to broadcast the
CHANGE event to the homemade function
changeSlider().
5. Test the movie by selecting Control, Test Movie. The user experience
is less than ideal because users have to let go of the slider to see the
myContent clip update. Change the code where it says CHANGE to in-
stead read
THUMB_DRAG. Test the movie again, and the clip should up-

date while you drag. If the user uses arrow keys to move the slider, a
feature that’s supported, the content doesn’t update at all. To fix this,
include two lines with
addEventListener(). That is, replace the sin-
gle line (line 5 in the code from step 4) with the following code:
mySlider.addEventListener(SliderEvent.THUMB_DRAG, changeSlider);
mySlider.addEventListener(SliderEvent.CHANGE, changeSlider);
Although two different events trigger the same code, it should work better.
From the Library of Lee Bogdanoff
ptg
341
Summary
Because you might be getting tired of that clip full of photos, here’s a vari-
ation on the previous task. The next code enables your user to change the
frame rate of your movie. Modify the
changeSlider function to read as
follows:
function changeSlider (evt){
stage.frameRate = mySlider.value
}
If you do this, you probably want different values for the Slide compo-
nent’s
minimum and maximum properties.
Summary
This hour you learned how to use some of the more advanced components.
Specifically, you’ve learned how a data provider gives you a way to store
data in a structured manner and then associate that data with one of the
list-based components. You’ve also learned how to customize the columns
in a DataGrid component.
The rest of the hour was spent learning how to apply several other compo-

nents. The ActionScript was kept to a minimum, but it still might have
been more than you had expected. If that was the case for you, you should
be glad to know the remaining hours are practically free of any complex
ActionScript.
From the Library of Lee Bogdanoff
ptg
342
HOUR 18: Using Components
Q&A
Q. I think working in Flash with components makes my computer run
slowly. What’s the deal?
A. The ActionScript 3.0 components for Flash CS4 run efficiently in the
.swfs that you create. However, one feature in particular makes the au-
thoring environment slow down; that feature is Live Preview. If you dese-
lect the option Control, Enable Live Preview, then you should see a great
performance boost while working with components in Flash.
Q.
I found some code using addChild() that was supposed to effectively
drag components onto the stage at runtime. Here’s the code, but why
doesn’t it work?
import fl.controls.Button;
var myButton:Button = new Button()
addChild(myButton)
myButton.label = “click me”
myButton.addEventListener(MouseEvent.CLICK, clickHandler )
function clickHandler ( evt ){
trace (“you clicked”)
}
A. The preceding code is perfect. However, you must ensure your Flash file
has a Button component present in its Library. Either drag one from the

Components panel to the Library panel or drag one from the Compo-
nents panel onto the Stage. Then, delete the one onstage as it’s now
safe in your Library.
Q.
In the first frame of my movie, I am using addItem() to populate my
List component. The problem is when I allow the user to navigate to
other frames, say Frame 2 and beyond, and then return to Frame 1, the
List keeps getting longer. Is there a way to add the items just once in-
stead of every time I come back to Frame 1?
A. First, this wouldn’t happen if your List component appears in one frame,
populates there, and then is not onstage in Frame 2 and beyond. You
could repopulate it every time the user navigates to a different frame. If
you want to keep the List present the whole time, you probably want to
make two changes. First, create a
DataProvider variable to maintain
the content, and assign the List’s
dataProvider property, as discussed
at the end of the section “Using Data Providers”. Second, create and
populate the
DataProvider once in Frame 1, then put your main con-
tent in Frame 2. When users navigate away, have them return to Frame
2 and not all the way back to Frame 1. This way your initial creation of
the
DataProvider occurs only once.
From the Library of Lee Bogdanoff
ptg
343
Workshop
Q. I used addEventListener() to broadcast an event, CHANGE, to my
custom function, but I want to change it while the movie plays to

broadcast to a different function. I noticed that Add Event Listener defi-
nitely doesn’t mean Replace Event Listener because when I add a sec-
ond listener, both custom functions trigger. Is there a way to redirect
the events so they broadcast to a different function?
A. We spent time discussing how to add event listeners, but never how to
remove them. It’s fairly straightforward. You can’t replace event listen-
ers—you just remove one and add another. To effectively turn off an
event listener, use
removeEventListener(). The two parameters are
identical to the two for
addEventListener()—namely, the event you no
longer want to listen for and the name of the custom function that is
handling the event. To summarize: To get rid of your old listener, use
removeEvent Listener(), and then you can use addEventListener()
to start broadcasting to a different function.
Workshop
The Workshop consists of quiz questions and answers to help you solidify
your understanding of the material covered in this hour. You should try to
answer the questions before checking the answers.
Quiz
1. In addition to populating your component instances, what step is nec-
essary to make the component do something when the user interacts
with it?
A. You need to enable interactivity on the component via the Com-
ponent Inspector panel.
B. You need to use addEventListener() to broadcast events to a cus-
tom function.
C. No step is necessary. Components are for visual display of infor-
mation, not functionality.
From the Library of Lee Bogdanoff

ptg
344
HOUR 18: Using Components
2. The ActionScript object that you pass as a parameter in the addItem()
method must always include a value for the label property.
A. Yes, otherwise you don’t see anything.
B. No, you can provide any properties you want.
C. You don’t have to, but if you’re using a List or ComboBox, then
you probably want to set the label to see anything.
3. Why is there so much ActionScript needed to use the components?
A. It’s not a that much, at least not compared to what you’d have to
do if you program the components from scratch.
B. The ActionScript makes Flash run faster.
C. It’s linked to early programmers who were primarily masochists.
Quiz Answers
1. B. Two parts include populating the component’s properties, such as
its label, and setting up listeners so your code hears the events as they
trigger.
2. C. Answer A is true if you’re using the List or ComboBox, and An-
swer B is true if you’re definitely not using one of those two compo-
nents. But, Answer C is the best answer.
3. A. The components are designed to work with the absolute minimum
of ActionScript. For better or worse, that means some coding is nec-
essary.
From the Library of Lee Bogdanoff
ptg
WHAT YOU’LL LEARN IN
THIS HOUR:
. How to import and use
video in movies

. How to include ad-
vanced features using
the FLVPlayback com-
ponent
. How to use cue points
to synchronize a video
to the graphics in your
Flash movie
. How to optimize for
high quality and low
file size
In the not-too-distant past, it was impossible to display video inside of
Flash without something short of a miracle. The video support in Flash has
really come of age. You can import video, trim it, and compress it, using the
state-of-the-art VP6 codec from On2 that keeps files small and quality high.
With this version of Flash, a new feature supports the H.264 video codec,
giving you a broader choice of content. Even though most of the technical
details are handled automatically, you’re given enough control to vary the
results greatly.
Codec is short for compressor/decompressor. Basically, videos need to be
compressed so they download quickly. The same video needs to be decom-
pressed for the user to view it. Many different technologies are available to
compress and decompress. The codec you must use if delivering to Flash
Player 7 is called Spark (from Sorenson), whereas Flash Professional 10 also
includes VP6 (from On2) and H.264.
Embedding Video Versus Playing
External Video
Two general ways to play video inside Flash are to embed where you im-
port, compress, and then place the video inside your main file, or compress
the video into an Flash video format (

.flv) file and play it externally. Exter-
nal
.flvs have the additional option to stream from a special server that
sends only the bits of the video as requested, making it possible for the user
to seek ahead in the clip. However, streaming requires a streaming server
(Flash Media Server or Red5) or a service provider who hosts your videos
on their streaming server. Without any additional software, Flash can play
videos only progressively, meaning they download from start to end. Pro-
HOUR 19
Using Video
From the Library of Lee Bogdanoff

×