1. Trang chủ
  2. » Công Nghệ Thông Tin

Flash CS4 Professional in 24 Hours- P12 pdf

30 319 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Using The Radiobutton Component
Trường học Lee Bogdanoff
Thể loại Hướng dẫn
Định dạng
Số trang 30
Dung lượng 534,44 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

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.. elemen

Trang 1

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 inser t a blank keyframe

by pressing F7 On the screen, you create the content for the Novice

Put some text onscreen that says ‘Welcome novice’ Inser t a blank

keyframe on Frame 3, and draw the content for the Intermediate user

Finally, on Frame 4, inser t a blank keyframe, and draw some content

for the Exper t 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:

function clickContinue ( evt ){

var frameNumber = 1 + Number( noviceButton.group.selectedData )

gotoAndStop ( frameNumber )

}

Trang 2

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 theComboBox, Button, and RadioButton gave you a solid foundation on thebasics Next hour, you get to create more complete examples and exploreother components Before then, in the rest of this hour, you learn ways tochange the component’s appearance

Changing Component Appearances

Components include code and graphics However, you can change both thestyle of various elements, such as the font for the labels, as well as any ofthe graphics, called skins, contained in the component For example, youcould use italic text for the label on a button Or modify the Button, so it iscircular In fact, you can change even more attributes, such as the way theComboBox 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 ponent’s skin Second, you see how you can use ActionScript to change anystyle element in the component, including text layout and skins

so the user can’t click it yet All three RadioButtons broadcast theirCLICK to the homemade function revealContinue That functiondoes nothing except enable the continueButtoninstance The

continueButtonbroadcasts its CLICK event to the homemade tionclickContinue It is inside that function that we first calculatethe frame number by adding 1 to the selectedDataproper ty of thegroup to which the noviceButtonis a par t It’s definitely weird thatwe’re using just the noviceButtoninstance, but notice we’re grabbingtheselectedData(that’s the data parameter from whichever button

func-in the group is currently selected) Because all the RadioButton func-stances are par t of the same group, it doesn’t matter which button weuse

in-4 Test your movie

Trang 3

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.

Trang 4

324 HOUR 17:Introducing Components

The reason we mentioned 9-slice scaling is because you see the nine sliceswhen 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 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

graph-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 withActionScript The big reason is you want to modify the text formatting, likefor 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

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.

Trang 5

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()andsetComponentStyle()

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 replacemyInstancewith the instance name of your

compo-nent, replacetheStylewith the supported style found in the Help files, and

replacevaluewith an actual value It turns out the most common style you’

are changing is thetextFormat However, when you set thetextFormat

style, you must set it equal to aTextFormatobject That is, you first create a

TextFormatinstance, modify it (such as by setting the font and size), and

then use it in place of the value when callingsetStyle() Here’s an

exam-ple that changes the font used for a RadioButton instance namedmyRB:

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

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)

Trang 6

326 HOUR 17:Introducing Components

Setting the Style of All ComponentsFinally, you can affect a style for all instances of all components with thefollowing 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 acomponent class, except we’re using the StyleManager’ssetStyle()

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 mer and nonprogrammer This hour you have learned how to populatecomponents manually by using the Component Inspector, as well as how topopulate components by using ActionScript In addition, you have learnedhow to use addEventListenerto make components trigger your own cus-tom code

program-This hour you have seen details of the ComboBox, Button, and RadioButtoncomponents You see many more components next hour This hour youhave also learned the basic scripts for changing the styles of components

Each time we had to do it from scratch Although the components arecustomizable (both as far as the content they display and the visualskins), sometimes you do need to build things from scratch

Trang 7

327Summary

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 ever ything 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 power ful 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

star ted with all the components They’re ver y 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 Proper ties 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 Librar y 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 par t of

the Duplicate Symbol dialog (expand it if it’s not visible) Click the option

Expor t for ActionScript (It also checks the Expor t 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)

Trang 8

1 The Button component is identical to the homemade Simple Buttonsbecause 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 tion of audio tracks

selec-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 exclusivechoices

Quiz Answers

1 C.The Button component has states for Up, Down, and Over—plusselected 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, andthe 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 inwhich multiple selections are possible, such as when choosing pizzatoppings like pepperoni, olives, and sausage

Trang 9

How to use additionaluser interface compo-nents

How to integrate ple components intopractical applications

multi-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 labelproperty 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

Trang 10

330 HOUR 18:Using Components

Entering values manually through the Component Inspector panel is fairlyintuitive As you recall from last hour, you selected a ComboBox instanceand clicked the dataProviderproperty in the Component Inspector panel

to reveal the values dialog, where you could add as a many label or datapairs 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 inspectthe current values, you have to return to the Component Inspector panel Amore significant disadvantage is you can’t make changes to the ComboBox’scontents while the movie plays

Using ActionScript to populate a component improves on some of the sues with using the Component Inspector For example, you can use

is-addItem()to populate the component Consider this code, which populates

a ComboBox instance named myCombo:

myCombo.addItem( { label: “Microsoft”, data: “http://www.microsoft.com” } )

myCombo.addItem( { label: “Adobe”, data: “http://www.adobe.com” } )

This code has exactly the same outcome as populating manually with theComponent Inspector panel As a reminder, you can ascertain the datavalue 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.

Trang 11

For example, last hour we used the following code to take the user to the

URL stored as the Valueproperty 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 labelproperty and a dataproperty 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 labeland a dataproperty, but you could add as many

ad-ditional properties as you’d like to suit the content You always want the

labelproperty, but you can add additional pieces of dataproperty 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 labelproperties 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 myComboinstance You can try it yourself by

cre-ating a ComboBox onstage with the instance name myComboand 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 )

}

Trang 12

332 HOUR 18:Using Components

You build some more practical applications in the tasks that appear laterthis hour You can grab any item’s properties by name by referring to the in-stance’sselectedItemproperty 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: TheComponent Inspector panel and using the addItem()method The advan-tages of addItem()are that you can see all the content in one place, and youcan add additional arbitrary properties to fit your content The last thing tosee is how to create a separate data provider variable that holds all the con-tent and then associate that variable with your component instance Thisenables you to maintain the data separate from any one component in-stance If the data changes, the component updates Plus, you can associateone data provider with multiple components It’s a nice way to separate thedata from a specific component instance

The code for populating a data provider is almost identical to that for ulating a component’s items That is, you useaddItem() However, youneed 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 addone step at the end to associate the data provider with your component

myCombo.dataProvider = myDataProvider;

You need the importstatement first so Flash knows what DataProvideris

In the end, there’s no effective difference between this code and the ous examples The difference is you can associate myDataProviderwithother components because it is a separate variable In addition, if you mod-ify the myDataProviderinstance (say, you update the ageproperty in one ofthe 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

previ-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 myComboinstance

Remember it star ts counting

with 0, not 1

Trang 13

Although the ComboBox is great when it’s needed, realize all the

informa-tion in this secinforma-tion 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 labelproperties 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 nent to Enable Users

Compo-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

ser ve 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 temporar y graphics we draw Select the drawn rectangle,

and conver t 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 myContentinstance 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 InIn-sert, Timeline, Layer, and make each

frame a keyframe Into each frame, either import a small photograph or

quickly draw a temporar y graphic, such as a rough 1, 2, 3, and so on

Trang 14

334 HOUR 18:Using Components

Feel free to modify the three lines starting myData.addItemwith contentthat matches your photos Most of this code should look familiar It’s a bitugly at the very bottom under //initialize, where the content and list ismade 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 toFrame 1, but rather to the frame number matching the frame property ofthe 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 ing code:

follow-//make the data:

import fl.data.DataProvider;

var myData:DataProvider = new DataProvider();

myData.addItem( {label:”Sunset”, frame:1, caption:”This is a set” } )

myData.addItem( {label:”Sunrise”, frame:2, caption:”This is a rise” } )

sun-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

Trang 15

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 sor t 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

Ngày đăng: 01/07/2014, 19:20