Reviews & Opinions
Independent and trusted. Read before buy Macromedia Flex 2 - Programming Actionscript 3 0!

Macromedia Flex 2 - Programming Actionscript 3 0


Bookmark
Macromedia Flex 2 - Programming Actionscript 3 0

Bookmark and Share

 

Macromedia Flex 2 - Programming Actionscript 3 0About Macromedia Flex 2 - Programming Actionscript 3 0
Here you can find all about Macromedia Flex 2 - Programming Actionscript 3 0 like manual and other informations. For example: review.

Macromedia Flex 2 - Programming Actionscript 3 0 manual (user guide) is ready to download for free.

On the bottom of page users can write a review. If you own a Macromedia Flex 2 - Programming Actionscript 3 0 please write about it to help other people.
[ Report abuse or wrong photo | Share your Macromedia Flex 2 - Programming Actionscript 3 0 photo ]

 

 

Manual

Preview of first few manual pages (at low quality). Check before download. Click to enlarge.
Manual - 1 page  Manual - 2 page  Manual - 3 page 

Download (English)
Macromedia Flex 2-programming Actionscript 3.0, size: 3.5 MB

 

Macromedia Flex 2 - Programming Actionscript 3 0

 

 

User reviews and opinions

<== Click here to post a new opinion, comment, review, etc.

Comments to date: 10. Page 1 of 1. Average Rating:
smkristensen 3:03am on Saturday, October 9th, 2010 
This is my first Wacom. It is much nicer than my off-market tablet, and rightfully so, but I suppose I expected more luxury out of the price.
mblibby 11:44am on Sunday, September 5th, 2010 
I have been using an Intuos 2 tablet for the ...  Spring loaded tip for digital designers looking to reduce hard clicks.
mikesg 9:28am on Saturday, August 21st, 2010 
This device its about....10=15% better in feel than a tablet. It will not solve your inability to make quality marks. I am a college student that is heavily into graphic and web design. This is my first pen tablet and I am positive I have made the right decision!
Cakeman 9:39pm on Tuesday, August 17th, 2010 
"very nice and responsive, only downfalls are small screen for the price... these tablet pads seem to be a little pricy for what they are i think... "Ok im only 13 but still I recomend this! "Great size. Not too big and not too small of an area to work with. I use it for touching up photographs on the computer and painting.
pharmiz 1:00am on Saturday, July 3rd, 2010 
I love the pen pad the size takes abit of getting used as I used the extra large size at work for several years but the medium is the perfect size for...
zed888 2:50pm on Tuesday, June 22nd, 2010 
Absolutely brilliant. I am using the display under MacOSX. Setting it up was a breeze - plug it in and install the drivers.
jwhentsch 2:44am on Sunday, June 6th, 2010 
This tablet is fantastic! I had a Bamboo and the Intous4 blows it away! Pros: I must have researched for days and could not pass this one by! Good deal for the price. The sound is alright, a little better than I expected.
seyacat 5:52pm on Sunday, April 25th, 2010 
Makes fine adjustments a snap. Upgraded from years of mousework and finally see what the big deal was! Good Control","Natural Feel
gnom 4:45am on Wednesday, March 17th, 2010 
This tablet is fantastic! I had a Bamboo and the Intous4 blows it away! I normally use a headphones when I want watch movies because I hate disturbing others when watching movies late night. So.
TimWhelan 3:57pm on Monday, March 15th, 2010 
Wacom Rocks I have had Wacom tablets for years. This product is great. The drivers are always the easiest to install. Intuos 2 pen The pen works fine. The only complaint I have is that the nib sometimes is too short. Great but... Amazon says that "This pressure-sensitive pen has the same feature set as the Cintiq Grip Pen.

Comments posted on www.ps2netdrivers.net are solely the views and opinions of the people posting them and do not necessarily reflect the views or opinions of us.

 

Documents

doc0

What computer programs do
First of all, its useful to have a conceptual idea of what a computer program is and what it does. There are two main aspects to a computer program:
A program is a series of instructions or steps for the computer to carry out. Each step ultimately involves manipulating some piece of information or data.
In a general sense, a computer program is just a list of step-by-step instructions that you give to the computer, which it performs one by one. Each individual instruction is known as a statement. As youll see throughout this manual, in ActionScript, each statement is written with a semicolon at the end. In essence, all that a given instruction in a program does is manipulate some bit of data thats stored in the computers memory. In a simple case, you might instruct the computer to add two numbers and store the result in its memory. In a more complex case, imagine there is a rectangle drawn on the screen, and you want to write a program to move it somewhere else on the screen. The computer is keeping track of certain information about the rectanglethe x, y coordinates where its located, how wide and tall it is, what color it is, and so forth. Each of those bits of information is stored somewhere in the computers memory. A program to move the rectangle to a different location would have steps like change the x coordinate to 200; change the y coordinate to 150 (in other words, specifying new values to be used for the x and y coordinates). Of course, the computer does something with this data to actually turn those numbers into the image that appears on the computer screen; but for the level of detail were interested in, its enough to know that the process of moving a rectangle on the screen really just involves changing bits of data in the computers memory.

ADOBE FLEX 3 10

Variables and constants
Since programming mainly involves changing pieces of information in the computers memory, there needs to be a way to represent a single piece of information in the program. A variable is a name that represents a value in the computers memory. As you write statements to manipulate values, you write the variables name in place of the value; any time the computer sees the variable name in your program, it looks in its memory and uses the value it finds there. For example, if you have two variables named value1 and value2, each containing a number, to add those two numbers you could write the statement:

String: a textual value, like a name or the text of a book chapter Numeric: ActionScript 3.0 includes three specific data types for numeric data:

ADOBE FLEX 3 11

Number: any numeric value, including values with or without a fraction int: an integer (a whole number without a fraction) uint: an unsigned integer, meaning a whole number that cant be negative
Boolean: a true-or-false value, such as whether a switch is on or whether two values are equal
The simple data types represent a single piece of information: for example, a single number or a single sequence of text. However, the majority of the data types defined in ActionScript could be described as complex data types, because they represent a set of values grouped together. For example, a variable with the data type Date represents a single valuea moment in time. Nevertheless, that date value is actually represented as several values: the day, month, year, hours, minutes, seconds, and so on, all of which are individual numbers. So while we think of a date as a single value (and we can treat it as a single value by creating a Date variable), internally the computer thinks of it as a group of several values that, put together, define a single date. Most of the built-in data types, as well as data types defined by programmers, are complex data types. Some of the complex data types you might recognize are:
MovieClip: a movie clip symbol TextField: a dynamic or input text field SimpleButton: a button symbol Date: information about a single moment in time (a date and time)
Two words that are often used as synonyms for data type are class and object. A class is simply the definition of a data typeits like a template for all objects of the data type, like saying all variables of the Example data type have these characteristics: A, B, and C. An object, on the other hand, is just an actual instance of a class; a variable whose data type is MovieClip could be described as a MovieClip object. The following are different ways of saying the same thing:
The data type of the variable myVariable is Number. The variable myVariable is a Number instance. The variable myVariable is a Number object. The variable myVariable is an instance of the Number class.

var someObj:Object; var someObj;
ActionScript 3.0, however, introduces the concept of untyped variables, which can be designated in the following two ways:
var someObj:*; var someObj;
An untyped variable is not the same as a variable of type Object. The key difference is that untyped variables can hold the special value undefined, while a variable of type Object cannot hold that value. You can define your own classes using the class keyword. You can declare class properties in three ways: constants can be defined with the const keyword, variables are defined with the var keyword, and getter and setter properties are defined by using the get and set attributes in a method declaration. You can declare methods with the function keyword.

ADOBE FLEX 3 35

You create an instance of a class by using the new operator. The following example creates an instance of the Date class called myBirthday.
var myBirthday:Date = new Date();

Packages and namespaces

Packages and namespaces are related concepts. Packages allow you to bundle class definitions together in a way that facilitates code sharing and minimizes naming conflicts. Namespaces allow you to control the visibility of identifiers, such as property and method names, and can be applied to code whether it resides inside or outside a package. Packages let you organize your class files, and namespaces let you manage the visibility of individual properties and methods.

Packages

Packages in ActionScript 3.0 are implemented with namespaces, but are not synonymous with them. When you declare a package, you are implicitly creating a special type of namespace that is guaranteed to be known at compile time. Namespaces, when created explicitly, are not necessarily known at compile time. The following example uses the package directive to create a simple package containing one class:
package samples { public class SampleCode { public var sampleGreeting:String; public function sampleFunction() { trace(sampleGreeting + " from sampleFunction()"); } } }
The name of the class in this example is SampleCode. Because the class is inside the samples package, the compiler automatically qualifies the class name at compile time into its fully qualified name: samples.SampleCode. The compiler also qualifies the names of any properties or methods, so that sampleGreeting and sampleFunction() become samples.SampleCode.sampleGreeting and samples.SampleCode.sampleFunction(), respectively. Many developers, especially those with Java programming backgrounds, may choose to place only classes at the top level of a package. ActionScript 3.0, however, supports not only classes at the top level of a package, but also variables, functions, and even statements. One advanced use of this feature is to define a namespace at the top level of a package so that it will be available to all classes in that package. Note, however, that only two access specifiers, public and internal, are allowed at the top level of a package. Unlike Java, which allows you to declare nested classes as private, ActionScript 3.0 supports neither nested nor private classes. In many other ways, however, ActionScript 3.0 packages are similar to packages in the Java programming language. As you can see in the previous example, fully qualified package references are expressed using the dot operator (.), just as they are in Java. You can use packages to organize your code into an intuitive hierarchical structure for use by other programmers. This facilitates code sharing by allowing you to create your own package to share with others, and to use packages created by others in your code.

addEventListener(MouseEvent.CLICK, clickListener);
The Array.sort() method also defines a parameter that accepts a function. For an example of a custom sort function that is used as an argument to the Array.sort() function, see Sorting an array on page 148. Although it may seem strange to programmers new to ActionScript, functions can have properties and methods, just as any other object can. In fact, every function has a read-only property named length that stores the number of parameters defined for the function. This is different from the arguments.length property, which reports the number of arguments sent to the function. Recall that in ActionScript, the number of arguments sent to a function can exceed the number of parameters defined for that function. The following example, which compiles only in standard mode because strict mode requires an exact match between the number of arguments passed and the number of parameters defined, shows the difference between the two properties:
// Compiles only in standard mode function traceLength(x:uint, y:uint):void { trace("arguments received: " + arguments.length); trace("arguments expected: " + traceLength.length); } traceLength(3, 5, 7, 11); /* output: arguments received: 4 arguments expected: 2 */
In standard mode you can define your own function properties by defining them outside your function body. Function properties can serve as quasi-static properties that allow you to save the state of a variable related to the function. For example, you may want to track the number of times a particular function is called. Such functionality could be useful if you are writing a game and want to track the number of times a user uses a specific command, although you could also use a static class property for this. The following example, which compiles only in standard mode because strict mode does not allow you to add dynamic properties to functions, creates a function property outside the function declaration and increments the property each time the function is called:
// Compiles only in standard mode var someFunction:Function = function ():void { someFunction.counter++; } someFunction.counter = 0; someFunction(); someFunction(); trace(someFunction.counter); // 2

ADOBE FLEX 3 83

Function scope
A functions scope determines not only where in a program that function can be called, but also what definitions the function can access. The same scope rules that apply to variable identifiers apply to function identifiers. A function declared in the global scope is available throughout your code. For example, ActionScript 3.0 contains global functions, such as isNaN() and parseInt(), that are available anywhere in your code. A nested functiona function declared within another functioncan be used anywhere in the function in which it was declared.

// creates a Date in local time var nextDay:Date = new Date("Mon May 11:30:00 AM"); // converts the Date to UTC by adding or subtracting the time zone offset var offsetMilliseconds:Number = nextDay.getTimezoneOffset() * 60 * 1000; nextDay.setTime(nextDay.getTime() + offsetMilliseconds);
When you develop applications using Adobe Flash CS3 Professional, you have access to the timeline, which provides a steady, frame-by-frame progression through your application. In pure ActionScript projects, however, you must rely on other timing mechanisms.

Loops versus timers

In some programming languages, you must devise your own timing schemes using loop statements like for or

do.while.

Loop statements generally execute as fast as the local machine allows, which means that the application runs faster on some machines and slower on others. If your application needs a consistent timing interval, you need to tie it to an actual calendar or clock time. Many applications, such as games, animations, and real-time controllers, need regular, time-driven ticking mechanisms that are consistent from machine to machine. The ActionScript 3.0 Timer class provides a powerful solution. Using the ActionScript 3.0 event model, the Timer class dispatches timer events whenever a specified time interval is reached.

The Timer class

The preferred way to handle timing functions in ActionScript 3.0 is to use the Timer class (flash.utils.Timer), which can be used to dispatch events whenever an interval is reached. To start a timer, you first create an instance of the Timer class, telling it how often to generate a timer event and how many times to do so before stopping. For example, the following code creates a Timer instance that dispatches an event every second and continues for 60 seconds:
var oneMinuteTimer:Timer = new Timer(1000, 60);
The Timer object dispatches a TimerEvent object each time the given interval is reached. A TimerEvent objects event type is timer (defined by the constant TimerEvent.TIMER). A TimerEvent object contains the same properties as a standard Event object. If the Timer instance is set to a fixed number of intervals, it will also dispatch a timerComplete event (defined by the constant TimerEvent.TIMER_COMPLETE) when it reaches the final interval.

ADOBE FLEX 3 126

Here is a small sample application showing the Timer class in action:
package { import flash.display.Sprite; import flash.events.TimerEvent; import flash.utils.Timer; public class ShortTimer extends Sprite { public function ShortTimer() { // creates a new five-second Timer var minuteTimer:Timer = new Timer(1000, 5); // designates listeners for the interval and completion events minuteTimer.addEventListener(TimerEvent.TIMER, onTick); minuteTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete); // starts the timer ticking minuteTimer.start(); } public function onTick(event:TimerEvent):void { // displays the tick count so far // The target of this event is the Timer instance itself. trace("tick " + event.target.currentCount); } public function onTimerComplete(event:TimerEvent):void { trace("Time's Up!"); } } }

Understanding the Graphics class
Each Shape, Sprite, and MovieClip object has a graphics property, which is an instance of the Graphics class. The Graphics class includes properties and methods for drawing lines, fills, and shapes. If you want a display object to use solely as a canvas for drawing content, you can use a Shape instance. A Shape instance will perform better than other display objects for drawing, because it doesnt have the overhead of the additional functionality in the Sprite and MovieClip classes. If you want a display object on which you can draw graphical content and also want that object to contain other display objects, you can use a Sprite instance. For more information on determining which display object to use for various tasks, see Choosing a DisplayObject subclass on page 264.

ADOBE FLEX 3 296

Drawing lines and curves
All drawing that you do with a Graphics instance is based on basic drawing with lines and curves. Consequently, all ActionScript drawing must be performed using the same series of steps:
Define line and fill styles Set the initial drawing position Draw lines, curves, and shapes (optionally moving the drawing point) If necessary, finish creating a fill
Defining line and fill styles
To draw with the graphics property of a Shape, Sprite, or MovieClip instance, you must first define the style (line size and color, fill color) to use when drawing. Just like when you use the drawing tools in Adobe Flash CS3 Professional or another drawing application, when youre using ActionScript to draw you can draw with or without a stroke, and with or without a fill color. You specify the appearance of the stroke using the lineStyle() or lineGradientStyle() method. To create a solid line, use the lineStyle() method. When calling this method, the most common values youll specify are the first three parameters: line thickness, color, and alpha. For example, this line of code tells the Shape named myShape to draw lines that are 2 pixels thick, red (0x990000), and 75% opaque:
myShape.graphics.lineStyle(2, 0x990000,.75);
The default value for the alpha parameter is 1.0 (100%), so you can leave that parameter off if you want a completely opaque line. The lineStyle() method also accepts two additional parameters for pixel hinting and scale mode; for more information about using those parameters see the description of the Graphics.lineStyle() method in the ActionScript 3.0 Language and Components Reference. To create a gradient line, use the lineGradientStyle() method. This method is described in Creating gradient lines and fills on page 299. If you want to create a filled shape, you call the beginFill(), beginGradientFill(), or beginBitmapFill() methods before starting the drawing. The most basic of these, the beginFill() method, accepts two parameters: the fill color, and (optionally) an alpha value for the fill color. For example, if you want to draw a shape with a solid green fill, you would use the following code (assuming youre drawing on an object named myShape):

If we were to create a second run-time library, we could create another FLA based upon another class (for example, AnimationAssets) that provides its own getAssets() implementation.
Creating classes for each MovieClip asset
For this example, well merely extend the MovieClip class without adding any functionality to the custom assets. The following code for AnimatingStar is analogous to that of AnimatingBox:
package com.example.programmingas3.runtimeassetexplorer { import flash.display.MovieClip; public class AnimatingStar extends MovieClip { public function AnimatingStar() { } } } Publishing the library
Well now connect the MovieClip-based assets to the new class by creating a new FLA and entering GeometricAssets into the Document Class field of the Property inspector. For the purposes of this example, well create two very basic shapes that use a timeline tween to make one clockwise rotation over 360 frames. Both the animatingBox and animatingStar symbols are set to Export for ActionScript and have the Class field set to the respective classpaths specified in the getAssets() implementation. The default base class of flash.display.MovieClip remains, as we want to subclass the standard MovieClip methods. After setting up your symbols export settings, publish the FLA. You now have your first run-time library. This SWF file could be loaded into another AVM2 SWF file and the AnimatingBox and AnimatingStar symbols would be available to the new SWF file.
Loading the library into another SWF file
The last functional piece to deal with is the user interface for the asset explorer. In this example, the path to the runtime library is hard-coded as a variable named ASSETS_PATH. Alternatively, you could use the FileReference class for example, to create an interface that browses for a particular SWF file on your hard drive.

ADOBE FLEX 3 354

When the run-time library is successfully loaded, Flash Player calls the runtimeAssetsLoadComplete() method:
private function runtimeAssetsLoadComplete(event:Event):void { var rl:* = event.target.content; var assetList:Array = rl.getAssets(); populateDropdown(assetList); stage.frameRate = 60; }
In this method, the variable rl represents the loaded SWF file. The code calls the getAssets() method of the loaded SWF file, obtaining the list of assets that are available, and uses them to populate a ComboBox component with a list of available assets by calling the populateDropDown() method. That method in turn stores the full classpath of each asset. Clicking the Add button on the user interface triggers the addAsset() method:

myTextBox.type = TextFieldType.INPUT; myTextBox.background = true; myTextBox.displayAsPassword = true; addChild(myTextBox);
The restrict property is a little more complicated since you need to specify what characters the user is allowed to type in an input text field. You can allow specific letters, numbers, or ranges of letters, numbers, and characters. The following code allows the user to enter only uppercase letters (and not numbers or special characters) in the text field:
myTextBox.restrict = A-Z;
ActionScript 3.0 uses hyphens to define ranges, and carets to define excluded characters. For more information about defining what is restricted in an input text field, see the flash.text.TextField.restrict property entry in the ActionScript 3.0 Language and Components Reference.

Formatting text

You have several options for programmatically formatting the display of text. You can set properties directly on the TextField instancefor example, the TextFIeld.thickness, TextField.textColor, and TextField.textHeight properties. Or you can designate the content of the text field using the htmlText property and use the supported HTML tags, such as b, i, and u. But you can also apply TextFormat objects to text fields containing plain text, or StyleSheet objects to text fields containing the htmlText property. Using TextFormat and StyleSheet objects provides the most control and consistency over the appearance of text throughout your application. You can define a TextFormat or StyleSheet object and apply it to many or all text fields in your application.

Assigning text formats

You can use the TextFormat class to set a number of different text display properties and to apply them to the entire contents of a TextField object, or to a range of text. The following example applies one TextFormat object to an entire TextField object and applies a second TextFormat object to a range of text within that TextField object:
var tf:TextField = new TextField(); tf.text = "Hello Hello"; var format1:TextFormat = new TextFormat(); format1.color = 0xFF0000; var format2:TextFormat = new TextFormat(); format2.font = "Courier"; tf.setTextFormat(format1); var startRange:uint = 6; tf.setTextFormat(format2, startRange); addChild(tf);

ADOBE FLEX 3 363

var format:TextFormat = new TextFormat(); format.color = 0x336699; format.size = 48; format.font = "myFont"; var myText:TextField = new TextField(); myText.embedFonts = true; myText.autoSize = TextFieldAutoSize.LEFT; myText.antiAliasType = AntiAliasType.ADVANCED; myText.defaultTextFormat = format; myText.selectable = false; myText.mouseEnabled = true; myText.text = "Hello World"; addChild(myText); myText.addEventListener(MouseEvent.CLICK, clickHandler); function clickHandler(event:Event):void { var myAntiAliasSettings = new CSMSettings(48, 0.8, -0.8); var myAliasTable:Array = new Array(myAntiAliasSettings); TextRenderer.setAdvancedAntiAliasingTable("myFont", FontStyle.ITALIC, TextColorType.DARK_COLOR, myAliasTable); }

Working with static text

Static text is created only within the Flash authoring tool. You cannot programmatically instantiate static text using ActionScript. Static text is useful if the text is very short and is not intended to change (as dynamic text can). Think of static text as a sort of graphic element like a circle or square drawn on the Stage in the Flash authoring tool. While static text is more limited than dynamic text, ActionScript 3.0 does support the ability to read the property values of static text using the flash.text.StaticText class. In addition, you can use the flash.text.TextSnapshot class to read values out of the static text.

ADOBE FLEX 3 368

Accessing static text fields with the StaticText class
Typically, you use the flash.text.StaticText class in the Actions panel of the Flash authoring tool to interact with a static text instance placed on the Stage. You may also work in ActionScript files that interact with a SWF file containing static text. In either case, you cant instantiate a static text instance programmatically. Static text is created in the Flash CS3 authoring tool. To create a reference to an existing static text field in ActionScript 3.0, you can iterate over the items in the display list and assign a variable. For example:
for (var i = 0; i < this.numChildren; i++) { var displayitem:DisplayObject = this.getChildAt(i); if (displayitem instanceof StaticText) { trace("a static text field is item " + i + " on the display list"); var myFieldLabel:StaticText = StaticText(displayitem); trace("and contains the text: " + myFieldLabel.text); } }
Once you have a reference to a static text field, you can use the properties of that field in ActionScript 3.0. The following code is attached to a frame in the Timeline, and assumes a variable named myFieldLabel assigned to a static text reference. In the example, a dynamic text field named myField is positioned relative to the x and y values of myFieldLabel and displays the value of myFieldLabel again.
var myField:TextField = new TextField(); addChild(myField); myField.x = myFieldLabel.x; myField.y = myFieldLabel.y + 20; myField.autoSize = TextFieldAutoSize.LEFT; myField.text = "and " + myFieldLabel.text

Every 1/10 of a second (100 milliseconds) the Timer objects timer event is dispatched and the timerHandler() function updates the text field on the display list.
Sending video to a server
If you want to build more complex applications involving video or camera objects, Flash Media Server offers a combination of streaming media capabilities and a development environment for creating and delivering media applications to a wide audience. This combination enables developers to create applications such as Video on Demand, live web-event broadcasts, and mp3 streaming as well as video blogging, video messaging, and multimedia chat environments. For more information, see the Flash Media Server documentation online at http://livedocs.macromedia.com/fms/2/docs/.

ADOBE FLEX 3 417

The following topics address some special issues for working with video.
Flash Player compatibility with encoded FLV files
Flash Player 7 supports FLV files that are encoded with the Sorenson Spark video codec. Flash Player 8 supports FLV files encoded with Sorenson Spark or On2 VP6 encoder in Flash Professional 8. The On2 VP6 video codec supports an alpha channel. Different Flash Player versions support FLV in different ways. For more information, see the following table:
Codec Sorenson Spark SWF file version (publish version) On2 VPFlash Player version required for playback 6, 7, or 8 7, 8 8* 8 8
*. If your SWF file loads an FLV file, you can use the On2 VP6 video without having to republish your SWF file for Flash Player 8, as long as users use Flash Player 8 to view your SWF file. Only Flash Player 8 supports publish and playback of On2 VP6 video. Flash Player 9.0.115.0 and later versions support files derived from the standard MPEG-4 container format including F4V, MP4, M4A, MOV, MP4V, 3GP, and 3G2 if they contain H.264 video and/or HEAAC v2 encoded audio. H.264 delivers higher quality video at lower bitrates when compared to the same encoding profile in Sorenson or On2. HEAAC v2 is an extension of AAC (a standard audio format defined in the MPEG-4 video standard) that uses Spectral Band Replication (SBR) and Parametric Stereo (PS) techniques to increase coding efficiency at low bitrates. To learn more about H.264 encoding, see Exploring Flash Player support for high-definition H.264 video and AAC audio.

import flash.media.Sound; import flash.media.SoundLoaderContext; import flash.net.URLRequest; var s:Sound = new Sound(); var req:URLRequest = new URLRequest("bigSound.mp3"); var context:SoundLoaderContext = new SoundLoaderContext(8000, true); s.load(req, context); s.play();
As playback continues, Flash Player and AIR try to keep the sound buffer at the same size or greater. If the sound data loads faster than the playback speed, playback will continue without interruption. However, if the data loading rate slows down because of network limitations, the playhead could reach the end of the sound buffer. If this happens, playback is suspended, though it automatically resumes once more sound data has been loaded. To find out if playback is suspended because Flash Player or AIR is waiting for data to load, use the Sound.isBuffering property.

ADOBE FLEX 3 431

Playing sounds
Playing a loaded sound can be as simple as calling the Sound.play() method for a Sound object, as follows:
var snd:Sound = new Sound(new URLRequest("smallSound.mp3")); snd.play();
When playing back sounds using ActionScript 3.0, you can perform the following operations:
Play a sound from a specific starting position Pause a sound and resume playback from the same position later Know exactly when a sound finishes playing Track the playback progress of a sound Change volume or panning while a sound plays
To perform these operations during playback, use the SoundChannel, SoundMixer, and SoundTransform classes. The SoundChannel class controls the playback of a single sound. The SoundChannel.position property can be thought of as a playhead, indicating the current point in the sound data thats being played. When an application calls the Sound.play() method, a new instance of the SoundChannel class is created to control the playback. Your application can play a sound from a specific starting position by passing that position, in terms of milliseconds, as the startTime parameter of the Sound.play() method. It can also specify a fixed number of times to repeat the sound in rapid succession by passing a numeric value in the loops parameter of the Sound.play() method. When the Sound.play() method is called with both a startTime parameter and a loops parameter, the sound is played back repeatedly from the same starting point each time, as shown in the following code:
var snd:Sound = new Sound(new URLRequest("repeatingSound.mp3")); snd.play(1000, 3);
In this example, the sound is played from a point one second after the start of the sound, three times in succession.

In the previous example, notice that the mouse event contains positional information about the click. The localX and localY properties contain the location of the click on the lowest child in the display chain. For example, clicking at the top-left corner of square reports local coordinates of [0,0] because that is the registration point of square. Alternatively, the stageX and stageY properties refer to the global coordinates of the click on the Stage. The same click reports [50,50] for these coordinates, because square was moved to these coordinates. Both of these coordinate pairs can be useful depending on how you want to respond to user interaction. The MouseEvent object also contains altKey, ctrlKey, and shiftKey Boolean properties. You can use these properties to check if the Alt, Ctrl, or Shift key is also being pressed at the time of the mouse click.
Creating drag-and-drop functionality
Drag-and-drop functionality allows users to select an object while pressing the left mouse button, move the object to a new location on the screen, and then drop it at the new location by releasing the left mouse button. The following code shows an example of this:
import flash.display.Sprite; import flash.events.MouseEvent; var circle:Sprite = new Sprite(); circle.graphics.beginFill(0xFFCC00); circle.graphics.drawCircle(0, 0, 40);

ADOBE FLEX 3 454

var target1:Sprite = new Sprite(); target1.graphics.beginFill(0xCCFF00); target1.graphics.drawRect(0, 0, 100, 100); target1.name = "target1"; var target2:Sprite = new Sprite(); target2.graphics.beginFill(0xCCFF00); target2.graphics.drawRect(0, 200, 100, 100); target2.name = "target2"; addChild(target1); addChild(target2); addChild(circle); circle.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown) function mouseDown(event:MouseEvent):void { circle.startDrag(); } circle.addEventListener(MouseEvent.MOUSE_UP, mouseReleased); function mouseReleased(event:MouseEvent):void { circle.stopDrag(); trace(circle.dropTarget.name); }
For more details, see Creating drag-and-drop interaction on page 266.
Customizing the mouse cursor
The mouse cursor (mouse pointer) can be hidden or swapped for any display object on the Stage. To hide the mouse cursor, call the Mouse.hide() method. Customize the cursor by calling Mouse.hide(), listening to the Stage for the MouseEvent.MOUSE_MOVE event, and setting the coordinates of a display object (your custom cursor) to the stageX and stageY properties of the event. The following example illustrates a basic execution of this task:
var cursor:Sprite = new Sprite(); cursor.graphics.beginFill(0x000000); cursor.graphics.drawCircle(0,0,20); cursor.graphics.endFill(); addChild(cursor); stage.addEventListener(MouseEvent.MOUSE_MOVE,redrawCursor); Mouse.hide(); function redrawCursor(event:MouseEvent):void { cursor.x = event.stageX; cursor.y = event.stageY; }

Working with exceptions and returns
You should check to see if the PrintJob.start() method returns true before executing addPage() and send() calls, in case the user has cancelled the print job. A simple way to check whether these methods have been cancelled before continuing is to wrap them in an if statement, as follows:
if (myPrintJob.start()) { // addPage() and send() statements here }
If PrintJob.start() is true, meaning the user has selected Print (or Flash Player or AIR has initiated a Print command), the addPage() and send() methods can be called. Also, to help manage the printing process, Flash Player and AIR throw exceptions for the PrintJob.addPage() method, so that you can catch errors and provide information and options to the user. If a PrintJob.addPage() method fails, you can also call another function or stop the current print job. You catch these exceptions by embedding addPage() calls within a try.catch statement, as in the following example. In the example, [params] is a placeholder for the parameters specifying the actual content you want to print:
if (myPrintJob.start()) { try { myPrintJob.addPage([params]); } catch (error:Error) { // Handle error, } myPrintJob.send(); }

ADOBE FLEX 3 511

After the print job starts, you can add the content using PrintJob.addPage() and see if that generates an exception (for example, if the user has cancelled the print job). If it does, you can add logic to the catch statement to provide the user (or Flash Player or AIR) with information and options, or you can stop the current print job. If you add the page successfully, you can proceed to send the pages to the printer using PrintJob.send(). If Flash Player or AIR encounters a problem sending the print job to the printer (for example, if the printer is offline), you can catch that exception, too, and provide the user (or Flash Player or AIR) with information or more options (such as displaying message text or providing an alert within the Flash animation). For example, you can assign new text to a text field in an if.else statement, as the following code shows:

doc1

Adobe Presents

Colin Moocks
ActionScript 3.0 From the Ground Up Tour
Materials provided by OReilly Media, Inc.

Welcome

Welcome to the ActionScript 3.0: From the Ground Up Tour! In collaboration with Colin Moock, FITC Design and Technology Events, OReilly, and participating academic institutions around the world, Adobe is thrilled to bring you this world-class day of training. Following the tradition of Flex Camp (http://flex.org/camp/) and the onAIR bus tour (http://onair.adobe.com/), this lecture is an important part of Adobes ongoing initiative to bring knowledge to the development community. At Adobe, we understand that a tool is only useful when you know how to use it. And were committed to helping you gain that knowledge. So sit back, get ready for a high-paced day of learning, and most of all have fun!

Key Learning

The following table lists some of todays most important concepts. Concept Classes are blueprints for objects. Example

class VirtualPet { }

Links and Resources
The entire set of notes for todays lecture are available at: http://moock.org/lectures/groundUpAS3 The code for the virtual zoo application can be obtained at: http://moock.org/eas3/examples/moock_eas3_examples/virtualzoo_final For a prose version of todays lecture in book form, see Colin Moocks Essential ActionScript 3.0 (OReilly, 2007). Details about the book are included on the back cover of this program. For more books on Adobe technologies, see the Adobe Developer Library series, at http://www.oreilly.com/store/series/adl.csp.
Objects (or instances) are the things in a program, such as a number, a car, a button, a point in time Some classes are built into ActionScript, others are custom-made. A package contains a class so its name doesnt conflict with other names.

new VirtualPet()

MovieClip, TextField, Sound, String
package zoo { class VirtualPet { } }
A constructor method initializes objects.
class VirtualPet { public function VirtualPet () {

Agenda

9:00-10:30 10:30-10:45 10:45-12:30 12:30-1:30 1:15-2:45 2:45-3:00 3:00-4:30 4:30-4:45 4:45-6:00 First Steps: Programming tools, classes and objects, packages Break Variables, values, references, methods Lunch Break Conditionals, loops, Boolean logic, encapsulation, static members In-Room Break Functions, inheritance, compilation, type annotations, datatypes Break Events, display, image loading, text, interactivity A variable is an identifier (name) associated with a value (an object). Variables do not store values; they merely refer to them. Local variables are temporary, used to track data within a method or function only. A function can generate a result known as a return value. A function is a reusable set of instructions.

// Initialization code }

function doSomething () { // Instructions go here } function square (x) { return x * x; } var pet = new VirtualPet();
var firstReferenceToPet = new VirtualPet(); var secondReferenceToPet = firstReferenceToPet; function square (x) { var total = x * x; return total; }
ActionScript 3.0 From the Ground Up
Concept Instance variables describe an objects characteristics

Example

class VirtualPet { private var petName; private var currentCalories; }
Concept In an instance method, this means the object through which the method was invoked
public function eat (numberOfCalories) { this.currentCalories += numberOfCalories; }
Instance methods define an objects behaviors (things it can do)
class VirtualPet { public function eat (numberOfCalories) { } }
In an constructor method, this means the object being initialized
public function VirtualPet () { this.petName = Stan; }
Static variables track information relating to entire class
class VirtualPet { private static var maxNameLength = 20; }
Inheritance is a relationship between two or more classes where one borrows (or inherits) the variable and method definitions of another
public class Food { } public class Apple extends Food { }
Static methods define behaviors relating to entire class An argument is a value passed to a method or function A parameter is a local variable defined in a method or function header, whose value is set via an argument The private modifier means access within this class only; protected means this class or subclasses; internal means this package; public means anywhere

Math.min(4, 5)

A datatype is a set of values. Every class defines a datatype: the set of instances of that class, plus instances of descendant classes. Type annotations tell the compiler the datatype of a variable, parameter, or function return value.

eat(100);

class VirtualPet { private var petName:String; }
public function eat (numberOfCalories) { }
The compiler uses type annotations to detect reference errors at compile time. A cast operation tells the compiler the datatype of a single value, and can result in a runtime type conversion. Every.swf file must have a main class. A.swf files main class must inherit from either Sprite or MovieClip. At runtime, Flash creates an instance of the.swf file main class automatically, then adds it to the screen (i.e., puts it on the display list). The display list is the hierarchy of all objects currently eligible for screen display in Flash Player.
1061: Call to a possibly undefined method eatt through a reference with static type zoo: VirtualPet. Apple(foodItem).hasWorm()
internal class VirtualPet { private var petName; public function eat (numberOfCalories) { } }
public class VirtualZoo extends Sprite { }
A conditional is a statement that executes once when a condition is met
if (testExpression) { codeBlock1 } else { codeBlock2 }
A loop is a statement that executes for as long as a condition is met
while (testExpression) { codeBlock }
Concept Key classes for displaying things include: DisplayObject: base display class InteractiveObject: adds mouse/keyboard functionality DisplayObjectContainer: adds containment for grouping Sprite: adds dragability, button-style interaction features MovieClip: adds timeline control To put an object on screen, use addChild() and removeChild(). To load an external display asset, use the Loader class.

Example

ActionScript Overview
ActionScript 3.0 is an object-oriented language for creating applications and scripted multimedia content for playback in Flash client runtimes (such as Flash Player and Adobe AIR). With a syntax reminiscent of Java and C#, ActionScripts core language should be familiar to experienced programmers. For example, the following code creates a variable named width, of type int (meaning integer), and assigns it the value 25:

var width:int = 25;

The following code creates a for loop that counts up to 10:
for (var i:int = 1; i <= 10; i++) { // Code here runs 10 times }
And the following code creates a class named Product:
graphicsContainer.addChild(hungryIcon); // The class definition public class Product { // An instance variable of type Number var price:Number; // The Product class constructor method public function Product () { // Code here initializes Product instances } // An instance method public function doSomething ():void { // Code here executes when doSomething() is invoked } }

petAlive = new Loader(); petAlive.load(new URLRequest( pet-alive.gif));
Event dispatching is a system for one object to tell other objects that something happened event: the thing that happened event target: the object to which the event pertains event listeners: methods that register to be notified of the event To register for an event, use addEventListener().

The Core Language

appleBtn.addEventListener(MouseEvent.CLICK, appleBtnClick);
ActionScript 3.0s core language is based on the ECMAScript 4th edition language specification, which is still under development as of October 2007.
The ECMAScript 4 specification can be viewed at http://developer. mozilla.org/es4/spec/spec.html. The ActionScript 3.0 specification can Remember, learning to program is a life-long process. be viewed at http://livedocs.macromedia.com/specs/actionscript/3.
In the future, ActionScript is expected to be a fully conforming implementation of ECMAScript 4. Like ActionScript, the popular web browser language JavaScript is also based on ECMAScript. The future Firefox 3.0 web browser is expected to implement JavaScript 2.0 using the same code base as ActionScript, which was contributed to the Mozilla Foundation by Adobe in November, 2006 (for information, see http://www.mozilla.org/projects/tamarin).
ECMAScript 4 dictates ActionScripts basic syntax and grammarthe code used to create things such as expressions, statements, variables, functions, classes, and objects. ECMAScript 4 also defines a small set of built-in datatypes for working with common values (such as String, Number, and Boolean). Some of ActionScript 3.0s key core-language features include: First-class support for common object-oriented constructs, such as classes, objects, and interfaces Single-threaded execution model Runtime type-checking Optional compile-time type-checking Dynamic features such as runtime creation of new constructor functions and variables Runtime exceptions Direct support for XML as a built-in datatype Packages for organizing code libraries Namespaces for qualifying identifiers Regular expressions All Flash client runtimes that support ActionScript 3.0 share the features of the core language in common.

Runtime APIs

Each Flash client runtime offers its own built-in set of functions, variables, classes, and objectsknown as its runtime API. Each Flash client runtimes API has its own name. For example, the Flash client runtime API defined by Flash Player is known as the Flash Player API. All Flash client runtime APIs share a core set of functionality in common. For example, every Flash client runtime uses the same basic set of classes for displaying content on screen and for dispatching events. Key features shared by all Flash client runtime APIs include: Graphics and video display A hierarchical event architecture Text display and input Mouse and keyboard control Network operations for loading external data and communicating with server-side applications Audio playback Printing Communicating with external local applications Programming utilities

Flash Runtime Clients

ActionScript programs can be executed in three different client runtime environments: Adobe AIR, Flash Player, and Flash Lite. Adobe AIR Adobe AIR runs Flash-platform applications intended for desktop deployment. Adobe AIR supports SWF-format content, as well as content produced with HTML and JavaScript. Adobe AIR must be installed directly on the end-users computer at the operating-system level. For more information, see http://www.adobe.com/go/air. Flash Player Flash Player runs Flash-platform content and applications intended for Web deployment. Flash Player is the runtime of choice for embedding SWF-format content on a web page. Flash Player is typically installed as a web browser add-on, but can also run in standalone mode. Flash Lite Flash Lite runs Flash-platform content and applications intended for mobile-device deployment. Due to the performance limitations of mobile devices, Flash Lite typically lags behind Flash Player and Adobe AIR in both speed and feature set. As of October 2007, Flash Lite does not yet support ActionScript 3.0. The preceding Flash client runtimes offer a common core set of functionality, plus a custom set of features that cater to the capabilities and security requirements of the runtime environment. For example, Adobe AIR, Flash Player, and Flash Lite all use the same syntax for creating a variable, but Adobe AIR includes window-management and filesystem APIs, Flash Lite can make a phone vibrate, and Flash Player imposes special web-centric security restrictions to protect the end-users privacy.

Components

In addition to the Flash client runtime APIs, Adobe also offers two different sets of components for accomplishing common programming tasks and building user interfaces. Flex Builder 2 and the free Flex 2 SDK include the Flex framework, which defines a complete set of user interface controls, such as RadioButton, CheckBox, and List. The Flash authoring tool provides a similar set of user interface components. The Flash authoring tools components combine code with manually created graphical assets that can be customized by Flash developers and designers. Both the Flex framework and the Flash authoring tools component set are written entirely in ActionScript 3.0. The user interface components in the Flex framework generally have more features than those in the Flash authoring tools component set and, therefore, also have a larger file size.

User interface components from the Flex framework cannot be used in the Flash authoring tool, but user interface components from the Flash authoring tool can be used (both legally and technically) with Flex Builder 2 and mxmlc.
The Flash File Format (SWF)
ActionScript code must be compiled into a.swf file for playback in one of Adobes Flash client runtimes. A.swf file can include both ActionScript bytecode and embedded assets (graphics, sound, video, and fonts). Some.swf files contain assets only, and no code, while others contain code only, and no assets. A single ActionScript program might reside entirely within a single.swf file, or it might be broken into multiple.swf files. When a program is broken into multiple.swf files, one specific.swf file provides the program point of entry, and loads the other.swf files as required. Breaking a complex program into multiple.swf files makes it easier to maintain and, for Internet-delivered applications, can give the user faster access to different sections of the program.
The Virtual Zoo Program Code
Example A-1 shows the code for the VirtualZoo class, the virtual zoo programs main class. Example A-1. The VirtualZoo class
package { import flash.display.Sprite; import zoo.*; import flash.events.*; public class VirtualZoo extends Sprite { private var pet:VirtualPet; private var petView:VirtualPetView; // Constructor public function VirtualZoo () { pet = new VirtualPet(Stan); petView = new VirtualPetView(pet); petView.addEventListener(Event.COMPLETE, petViewCompleteListener); } public function petViewCompleteListener (e:Event):void { addChild(petView); pet.start(); } } }
ActionScript Development Tools
Adobe offers the following tools for creating ActionScript code: Adobe Flash http://www.adobe.com/go/flash/ A visual design and programming tool for creating multimedia content that integrates graphics, video, audio, animation, and interactivity. In Adobe Flash, developers create interactive content by combining ActionScript code with animation, manually created content, and embedded assets. Adobe Flash is also known as the Flash authoring tool. As of October 2007, the latest version of the Flash authoring tool is Flash CS3 (version 9 of the software). Adobe Flex Builder http://www.adobe.com/products/flex/productinfo/overview/ A development tool for producing content using either pure ActionScript or MXML, an XML-based language for describing user interfaces. Flex Builder includes a development framework known as the Flex framework, which provides an extensive set of programming utilities and a library of skinnable, styleable user-interface controls. Based on Eclipse, the popular opensource programming tool, Flex Builder 2 can be used in either hand-coding mode or in a visual-development mode similar to Microsofts Visual Basic. Adobe Flex 2 SDK http://www.adobe.com/go/flex2_sdk A free command-line toolkit for creating content using either pure ActionScript 3.0 or MXML. The Flex 2 SDK includes the Flex framework and a command-line compiler, mxmlc (both of which are also included with Adobe Flex Builder 2). Using the Flex 2 SDK, developers can create content for free in the programming editor of their choice. (For a wide variety of opensource tools and utilities for ActionScript development, see http://osflash.org.)

Example A-2 shows the code for the VirtualPet class, whose instances represent pets in the zoo. Example A-2. The VirtualPet class
package zoo { import flash.utils.*; import flash.events.*; public class VirtualPet extends EventDispatcher { public static const NAME_CHANGE:String = NAME_CHANGE; public static const STATE_CHANGE:String = STATE_CHANGE; public public public public private private private private private private private private static static static static static static static static var var var var const const const const var var var var PETSTATE_FULL:int PETSTATE_HUNGRY:int PETSTATE_STARVING:int PETSTATE_DEAD:int = = = = 0; 1; 2; 3;
maxNameLength:int = 20; maxCalories:int = 2000; caloriesPerSecond:int = 100; defaultName:String = Unnamed Pet;
petName:String; currentCalories:int; petState:int; digestTimer:Timer;
public function VirtualPet (name:String):void { setName(name); setCalories(VirtualPet.maxCalories/2); } public function start ():void {
digestTimer = new Timer(1000, 0); digestTimer.addEventListener(TimerEvent.TIMER, digestTimerListener); digestTimer.start(); } public function stop ():void { if (digestTimer != null) { digestTimer.stop(); } } public function setName (newName:String):void { if (newName.indexOf( ) == 0) { throw new VirtualPetNameException(); } else if (newName == ) { throw new VirtualPetInsufficientDataException(); } else if (newName.length > VirtualPet.maxNameLength) { throw new VirtualPetExcessDataException(); } petName = newName; dispatchEvent(new Event(VirtualPet.NAME_CHANGE)); } public function getName ():String { if (petName == null) { return VirtualPet.defaultName; } else { return petName; } } public function eat (foodItem:Food):void { if (petState == VirtualPet.PETSTATE_DEAD) { trace(getName() + is dead. You cant feed it.); return; } if (foodItem is Apple) { if (Apple(foodItem).hasWorm()) { trace(The + foodItem.getName() + had a worm. + getName() + didnt eat it.); return; } } trace(getName() + ate the + foodItem.getName() + ( + foodItem.getCalories() + calories).); setCalories(getCalories() + foodItem.getCalories()); } } private function setCalories (newCurrentCalories:int):void { if (newCurrentCalories > VirtualPet.maxCalories) { currentCalories = VirtualPet.maxCalories; } else if (newCurrentCalories < 0) { currentCalories = 0; } else { currentCalories = newCurrentCalories; } } } }

var caloriePercentage:int = Math.floor(getHunger()*100); trace(getName() + has + currentCalories + calories + ( + caloriePercentage + % of its food) remaining.); if (caloriePercentage == 0) { if (getPetState() != VirtualPet.PETSTATE_DEAD) { die(); } } else if (caloriePercentage < 20) { if (getPetState() != VirtualPet.PETSTATE_STARVING) { setPetState(VirtualPet.PETSTATE_STARVING); } } else if (caloriePercentage < 50) { if (getPetState() != VirtualPet.PETSTATE_HUNGRY) { setPetState(VirtualPet.PETSTATE_HUNGRY); } } else { if (getPetState() != VirtualPet.PETSTATE_FULL) { setPetState(VirtualPet.PETSTATE_FULL); } }
public function getCalories ():int { return currentCalories; } public function getHunger ():Number { return currentCalories / VirtualPet.maxCalories; } private function die ():void { stop(); setPetState(VirtualPet.PETSTATE_DEAD); trace(getName() + has died.); } private function digest ():void { trace(getName() + is digesting.); setCalories(getCalories() - VirtualPet.caloriesPerSecond); } private function setPetState (newState:int):void { if (newState == petState) { return; } petState = newState; dispatchEvent(new Event(VirtualPet.STATE_CHANGE));
public function getPetState ():int { return petState; } private function digestTimerListener (e:TimerEvent):void { digest(); }
Example A-3 shows the code for the Food class, the superclass of the various types of food that pets eat. Example A-3. The Food class
package zoo { public class Food { private var calories:int; private var name:String; public function Food (initialCalories:int) { setCalories(initialCalories); } public function getCalories ():int { return calories; }
Finally, Example A-5 shows the code for the Sushi class, which represents a specific type of food that pets eat. Example A-5. The Sushi class
package zoo { public class Sushi extends Food { private static var DEFAULT_CALORIES:int = 500; public function Sushi (initialCalories:int = 0) { if (initialCalories <= 0) { initialCalories = Sushi.DEFAULT_CALORIES; } super(initialCalories); setName(Sushi); } } }
public function setCalories (newCalories:int):void { calories = newCalories; } public function getName ():String { return name; } public function setName (newName:String):void { name = newName; } } }
Example A-6 shows the code for the VirtualPetNameException class, which represents an exception thrown when an invalid pet name is specified. Example A-6. The VirtualPetNameException class
package zoo { public class VirtualPetNameException extends Error { public function VirtualPetNameException ( message:String = Invalid pet name specified.) { super(message); } } }
Example A-4 shows the code for the Apple class, which represents a specific type of food that pets eat. Example A-4. The Apple class

package zoo { public class Apple extends Food { private static var DEFAULT_CALORIES:int = 100; private var wormInApple:Boolean; public function Apple (initialCalories:int = 0) { if (initialCalories <= 0) { initialCalories = Apple.DEFAULT_CALORIES; } super(initialCalories); wormInApple = Math.random() >=.5; setName(Apple); } public function hasWorm ():Boolean { return wormInApple; } } }
Example A-7 shows the code for the VirtualPetExcessDataException class, which represents an exception thrown when an excessively long pet name is specified for a pet. Example A-7. The VirtualPetExcessDataException class
package zoo { public class VirtualPetExcessDataException extends VirtualPetNameException public function VirtualPetExcessDataException () { super(Pet name too long.); } } }
Example A-8 shows the code for the VirtualPetInsufficientDataException class, which represents an exception thrown when an excessively short pet name is specified for a pet. Example A-8. The VirtualPetInsufficientDataException class
package zoo { public class VirtualPetInsufficientDataException extends VirtualPetNameException public function VirtualPetInsufficientDataException () { super(Pet name too short.); } } }
Example A-9 shows the code for the VirtualPetView class, which graphically displays a VirtualPet instance. Example A-9. The VirtualPetView class
package zoo { import flash.display.*; import flash.events.*; import flash.net.*; import flash.text.*; public class VirtualPetView extends Sprite { private var pet:VirtualPet; private var graphicsContainer:Sprite; private private private private private var var var var var petAlive:Loader; petDead:Loader; foodHungry:Loader; foodStarving:Loader; petName:TextField; // // // // // The pet in its alive state The pet in its alive state An icon for the hungry state An icon for the starving state Displays the pets name
private function createUI ():void { appleBtn = new FoodButton(Feed Apple); appleBtn.y = 170; appleBtn.addEventListener(MouseEvent.CLICK, appleBtnClick); addChild(appleBtn); sushiBtn = new FoodButton(Feed Sushi); sushiBtn.y = 190; sushiBtn.addEventListener(MouseEvent.CLICK, sushiBtnClick); addChild(sushiBtn); } private function disableUI ():void { appleBtn.disable(); sushiBtn.disable(); } private function loadGraphics ():void { petAlive = new Loader(); petAlive.load(new URLRequest(pet-alive.gif)); petAlive.contentLoaderInfo.addEventListener(Event.COMPLETE, completeListener); petAlive.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorListener); petDead = new Loader(); petDead.load(new URLRequest(pet-dead.gif)); petDead.contentLoaderInfo.addEventListener(Event.COMPLETE, completeListener); petDead.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorListener); foodHungry = new Loader(); foodHungry.load(new URLRequest(food-hungry.gif)); foodHungry.contentLoaderInfo.addEventListener(Event.COMPLETE, completeListener); foodHungry.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorListener); foodHungry.x = 15; foodHungry.y = 100; foodStarving = new Loader(); foodStarving.load(new URLRequest(food-starving.gif)); foodStarving.contentLoaderInfo.addEventListener(Event.COMPLETE, completeListener); foodStarving.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorListener); foodStarving.x = 15; foodStarving.y = 100; } private function petStateChangeListener (e:Event):void { if (pet.getPetState() == VirtualPet.PETSTATE_DEAD) { disableUI(); } renderCurrentPetState(); }

private var appleBtn:FoodButton; private var sushiBtn:FoodButton;
// Button for feeding the pet an apple // Button for feeding the pet sushi
// Load completion detection static private var numGraphicsToLoad:int = 4; private var numGraphicsLoaded:int = 0; public function VirtualPetView (pet:VirtualPet) { this.pet = pet; pet.addEventListener(VirtualPet.NAME_CHANGE, petNameChangeListener); pet.addEventListener(VirtualPet.STATE_CHANGE, petStateChangeListener); createGraphicsContainer(); createNameTag(); createUI(); loadGraphics(); } private function createGraphicsContainer ():void { graphicsContainer = new Sprite(); addChild(graphicsContainer); } private function createNameTag ():void { petName = new TextField(); petName.defaultTextFormat = new TextFormat(_sans,14,0x006666,true); petName.autoSize = TextFieldAutoSize.CENTER; petName.selectable = false; petName.x = 250; petName.y = 20; addChild(petName); }
private function renderCurrentPetState ():void { for (var i:int = graphicsContainer.numChildren-1; i >= 0; i--) { graphicsContainer.removeChildAt(i); } var state:int = pet.getPetState(); switch (state) { case VirtualPet.PETSTATE_FULL: graphicsContainer.addChild(petAlive); break; case VirtualPet.PETSTATE_HUNGRY: graphicsContainer.addChild(petAlive); graphicsContainer.addChild(foodHungry); break; case VirtualPet.PETSTATE_STARVING: graphicsContainer.addChild(petAlive); graphicsContainer.addChild(foodStarving); break; case VirtualPet.PETSTATE_DEAD: graphicsContainer.addChild(petDead); break; } } private function petNameChangeListener (e:Event):void { renderCurrentPetName(); } private function renderCurrentPetName ():void { petName.text = pet.getName(); } private function appleBtnClick (e:MouseEvent):void { pet.eat(new Apple()); } private function sushiBtnClick (e:MouseEvent):void { pet.eat(new Sushi()); } private function completeListener (e:Event):void { numGraphicsLoaded++; if (numGraphicsLoaded == numGraphicsToLoad) { renderCurrentPetState(); renderCurrentPetName(); dispatchEvent(new Event(Event.COMPLETE)); } } private function ioErrorListener (e:IOErrorEvent):void { trace(Load error: + e); } } }
Example A-10 shows the code for the FoodButton class, which represents a simple clickable-text button. Example A-10. The FoodButton class
package zoo { import flash.display.* import flash.events.*; import flash.text.*; public class FoodButton extends Sprite { private var text:TextField; private var upFormat:TextFormat; private var overFormat:TextFormat; public function FoodButton (label:String) { buttonMode = true; mouseChildren = false; upFormat = new TextFormat(_sans,12,0x006666,true); overFormat = new TextFormat(_sans,12,0x009999,true); text = new TextField(); text.defaultTextFormat = upFormat; text.text = label; text.autoSize = TextFieldAutoSize.CENTER; text.selectable = false; addChild(text); addEventListener(MouseEvent.MOUSE_OVER, mouseOverListener); addEventListener(MouseEvent.MOUSE_OUT, mouseOutListener); } public function disable ():void { mouseEnabled = false; } public function mouseOverListener (e:MouseEvent):void { text.setTextFormat(overFormat); } public function mouseOutListener (e:MouseEvent):void { text.setTextFormat(upFormat); } } }

Two years in the making, Essential ActionScript 3.0 is Colin Moocks complete guide to ActionScript 3.0. It covers programming fundamentals in truly exhaustive detail, with extreme clarity and precision. Its unparalleled accuracy and depth is the result of an entire decade of daily ActionScript research, realworld programming experience, and unmitigated insider-access to Adobes engineers. Every word of Essential ActionScript 3 has been carefully reviewedin many cases several times overby key members of Adobes engineering staff, including those on the Flash Player, Flex Builder, and Flash authoring teams. If you already have existing ActionScript experience, Essential ActionScript 3.0 will help you fill in gaps in your knowledge, rethink important concepts informal terms, and understand difficult subjects through plain, careful language. Consider Essential ActionScript 3.0 an ActionScript expert that sits with you at your desk. You might ask it to explain the subtleties of ActionScripts event architecture, or unravel the intricacies of Flash Players security system, or demonstrate the power of ActionScripts native XML support (E4X). Or you might turn to Essential ActionScript 3.0 for information on under-documented topics, such as namespaces, embedded fonts, loaded-content access, class-library distribution, garbage collection, and screen updates. Essential ActionScript 3.0 is a true developers handbook, packed with practical explanations, insightful warnings, and useful example code that demonstrates how to get the job done right.

ADOBE DEVELOPER LIBRARY

Adobe Developer Library, a co-publishing partnership between OReilly Media and Adobe Systems, Inc., is the authoritative resource for developers using Adobe technologies. With top-quality books and innovative online resources, the Adobe Developer Library delivers expert training straight from the source. Topics include ActionScript, Adobe Flex Adobe Flash, and Adobe Apollo software. , Get the latest news about books, online resources, and more at adobedeveloperlibrary.com
Sponsored by Adobe Produced by FITC. Handouts and books provided by OReilly.
2007 OReilly Media, Inc. OReilly logo is a registered trademark of OReilly Media, Inc. All other trademarks are the property of their respective owners. 70613

 

Tags

ES-GA21 4X4-2000 CLP-760 Review KRC-778R Ulta III Portege 7010 CU-L43dbe5 AVR-1403 CS186 Apple Emac Watch Deluxe-2006 26PF5320 RME700 Wrxs3 Year Door For Ps2 FX770 SPC1030NC Tl92270 PX-E860 D6160 RC-1082 KV-32FQ86U Dxai4588-2 B243W L60840 GNC 420 26LB76 MF4690 IR310CD RE-32FZ30RQ Camera Spec-2 Stratoliner-2006 Series AQ18NSA VGN-NS21e S DMC-FX07 37LH3000 DZ9311P N73 Edge Babyface 7145I Gev2 VGN-FS215B Lrsc26920TT ML-2552W SCS500 5 N93-1 CD880 IT563N DVP5990K S3PRO 2232C Destiny ICF-C233 LS-H246tnb0 TLX Ps12 Adapter-d300 ME-20 DCR-PC115 SA-AK57 Machine LFA-PC20 Motorola D811 PS 2 Silver Acoustics SL60 DMC-FX580 Lide 600F DDX7019 Chair 4702-III Xterra-2001 SA-330 Automatic-2008 AV8003 ECM8000 IC-M120 KV-29LS35K FA1026hdro MD 5093 DES-5200 6420FF Panda CDJ-350 FX400 DVD-P560 Crocodile A3000 I915G Reference S500I FS-85USB PCR-500 UT21006 Amarys 1200 KAC-8404 Aw II LV-X6

 

manuel d'instructions, Guide de l'utilisateur | Manual de instrucciones, Instrucciones de uso | Bedienungsanleitung, Bedienungsanleitung | Manual de Instruções, guia do usuário | инструкция | návod na použitie, Užívateľská príručka, návod k použití | bruksanvisningen | instrukcja, podręcznik użytkownika | kullanım kılavuzu, Kullanım | kézikönyv, használati útmutató | manuale di istruzioni, istruzioni d'uso | handleiding, gebruikershandleiding

 

Sitemap

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101