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:
iamalwaysiam 2:07pm on Wednesday, November 3rd, 2010 
This tablet is fantastic! I had a Bamboo and the Intous4 blows it away! 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!
jgrainger 7:44am on Friday, October 22nd, 2010 
Amazing Simply put, this tablet is amazing. I went from using the Intuos2 to this tablet and I was blown away. Great but... Amazon says that "This pressure-sensitive pen has the same feature set as the Cintiq Grip Pen.
Davee 9:11am on Sunday, October 17th, 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.
venildo 6:26pm on Sunday, September 12th, 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.
Drax 9:29am on Wednesday, May 5th, 2010 
I have been using an Intuos 2 tablet for the ...  Spring loaded tip for digital designers looking to reduce hard clicks.
joydeeph 12:52am on Monday, April 19th, 2010 
As posted in the weakness column they should change this stand a little so you can tilt this all the way up to 90 degrees so you can use it as a regul... As far as drawing digitally goes, this is by far the best thing out there. When compared to the 6x8 wacom tablet. Absolutely brilliant. I am using the display under MacOSX. Setting it up was a breeze - plug it in and install the drivers.
jslegers 4:05am on Monday, March 29th, 2010 
If you like drawing or painting or editing photos like myself,This my friend is for you! Yes it is a bit steep in price.
dsjvicar 3:27am on Friday, March 26th, 2010 
Wonderful blue tooth headphones for the price. Great sound quality, keeps sound out and very comfortable Last only about one year if used every day I have been using an Intuos 2 tablet for the past 8 years (yes they were sold in 2002). From experience.
Paulpars 1:56am on Sunday, March 21st, 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...
Manuel_B 5:20pm on Tuesday, March 16th, 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!

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

class A {} class B extends A {} var objA:A = new A(); var objB:B = new B(); var arr:Array = new Array(); objA = objB; // Conversion succeeds. objB = arr; // Conversion fails.
For primitive types, implicit conversions are handled by calling the same internal conversion algorithms that are called by the explicit conversion functions. The following sections discuss these primitive type conversions in detail.

ADOBE FLEX 3 56

Explicit conversions
Its helpful to use explicit conversions, or casting, when you compile in strict mode, because there may be times when you do not want a type mismatch to generate a compile-time error. This may be the case when you know that coercion will convert your values correctly at run time. For example, when working with data received from a form, you may want to rely on coercion to convert certain string values to numeric values. The following code generates a compile-time error even though the code would run correctly in standard mode:
var quantityField:String = "3"; var quantity:int = quantityField; // compile time error in strict mode
If you want to continue using strict mode, but would like the string converted to an integer, you can use explicit conversion, as follows:
var quantityField:String = "3"; var quantity:int = int(quantityField); // Explicit conversion succeeds. Casting to int, uint, and Number
You can cast any data type into one of the three number types: int, uint, and Number. If Flash Player or Adobe AIR is unable to convert the number for some reason, the default value of 0 is assigned for the int and uint data types, and the default value of NaN is assigned for the Number data type. If you convert a Boolean value to a number, true becomes the value 1 and false becomes the value 0.
var myBoolean:Boolean = true; var myUINT:uint = uint(myBoolean); var myINT:int = int(myBoolean); var myNum:Number = Number(myBoolean); trace(myUINT, myINT, myNum); // 1 myBoolean = false; myUINT = uint(myBoolean); myINT = int(myBoolean); myNum = Number(myBoolean); trace(myUINT, myINT, myNum); // 0
String values that contain only digits can be successfully converted into one of the number types. The number types can also convert strings that look like negative numbers or strings that represent a hexadecimal value (for example, 0x1A). The conversion process ignores leading and trailing white space characters in the string value. You can also cast strings that look like floating-point numbers using Number(). The inclusion of a decimal point causes uint() and int() to return an integer, truncating the decimal and the characters following it. For example, the following string values can be cast into numbers:

One case in which you must use a function expression is when you choose to attach a function to the prototype object. For more information, see The prototype object on page 112.

Constructor methods

Constructor methods, sometimes simply called constructors, are functions that share the same name as the class in which they are defined. Any code that you include in a constructor method is executed whenever an instance of the class is created with the new keyword. For example, the following code defines a simple class named Example that contains a single property named status. The initial value of the status variable is set inside the constructor function.

ADOBE FLEX 3 92

class Example { public var status:String; public function Example() { status = "initialized"; } } var myExample:Example = new Example(); trace(myExample.status); // output: initialized
Constructor methods can only be public, but the use of the public attribute is optional. You cannot use any of the other access control specifiers, including private, protected, or internal, on a constructor. You also cannot use a user-defined namespace with a constructor method. A constructor can make an explicit call to the constructor of its direct superclass by using the super() statement. If the superclass constructor is not explicitly called, the compiler automatically inserts a call before the first statement in the constructor body. You can also call methods of the superclass by using the super prefix as a reference to the superclass. If you decide to use both super() and super in the same constructor body, be sure to call super() first. Otherwise, the super reference will not behave as expected. The super() constructor should also be called before any throw or return statement. The following example demonstrates what happens if you attempt to use the super reference before calling the
super() constructor. A new class, ExampleEx, extends the Example class. The ExampleEx constructor attempts to
access the status variable defined in its superclass, but does so before calling super(). The trace() statement inside the ExampleEx constructor produces the value null, because the status variable is not available until the super() constructor executes.
class ExampleEx extends Example { public function ExampleEx() { trace(super.status); super(); } } var mySample:ExampleEx = new ExampleEx(); // output: null
Although it is legal to use the return statement inside a constructor, it is not permissible to return a value. In other words, return statements must not have associated expressions or values. Accordingly, constructor methods are not allowed to return values, which means that no return type may be specified. If you do not define a constructor method in your class, the compiler will automatically create an empty constructor for you. If your class extends another class, the compiler will include a super() call in the constructor it generates.

ADOBE FLEX 3 161

Example: PlayList
The PlayList example demonstrates techniques for working with arrays, in the context of a music playlist application that manages a list of songs. These techniques are:
Creating an indexed array Adding items to an indexed array Sorting an array of objects by different properties, using different sorting options Converting an array to a character-delimited string
To get the application files for this sample, see www.adobe.com/go/learn_programmingAS3samples_flash. The PlayList application files can be found in the Samples/PlayList folder. The application consists of the following files:
File PlayList.mxml or PlayList.fla com/example/programmingas3/playlist/Song.as com/example/programmingas3/playlist/SortProperty.as A value object representing information about a single song. The items that are managed by the PlayList class are Song instances. A pseudo-enumeration whose available values represent the properties of the Song class by which a list of Song objects can be sorted. Description The main application file in Flash (FLA) or Flex (MXML).

PlayList class overview

The PlayList class manages a set of Song objects. It has public methods with functionality for adding a song to the playlist (the addSong() method) and sorting the songs in the list (the sortList() method). In addition, the class includes a read-only accessor property, songList, which provides access to the actual set of songs in the playlist. Internally, the PlayList class keeps track of its songs using a private Array variable:
public class PlayList { private var _songs:Array; private var _currentSort:SortProperty = null; private var _needToSort:Boolean = false;. }
In addition to the _songs Array variable, which is used by the PlayList class to keep track of its list of songs, two other private variables keep track of whether the list needs to be sorted (_needToSort) and which property the song list is sorted by at a given time (_currentSort). As with all objects, declaring an Array instance is only half the job of creating an Array. Before accessing an Array instances properties or methods, it must be instantiated, which is done in the PlayList classs constructor.
public function PlayList() { this._songs = new Array(); // Set the initial sorting. this.sortList(SortProperty.TITLE); }
The first line of the constructor instantiates the _songs variable, so that it is ready to be used. In addition, the sortList() method is called to set the initial sort-by property.

Error classes: Many errors have an error class associated with them. When an error occurs, Flash Player or Adobe AIR creates an instance of the specific error class that is associated with that particular error. Your code can use the information contained in that error object to make an appropriate response to the error. Error events: Sometimes an error occurs when Flash Player or Adobe AIR would normally trigger an event. In those cases, Flash Player and Adobe AIR trigger an error event instead. Like other events, each error event has a class associated with it, and Flash Player and Adobe AIR pass an instance of that class to the methods that are subscribed to the error event.
To determine whether a particular method can trigger an error or error event, see the methods entry in the ActionScript 3.0 Language and Components Reference.
Common error-handling tasks
These are common error-related tasks you might need to perform with your code:
Writing code to handle errors Testing for, catching, and re-throwing errors Defining your own error class Responding to error and status events
Asynchronous: A program command such as a method call that doesnt provide an immediate result; instead it gives a result (or error) in the form of an event. Catch: When an exception (a run-time error) occurs and your code becomes aware of the exception, that code is said to catch the exception. Once an exception is caught, Flash Player and Adobe AIR stop notifying other ActionScript code of the exception. Debugger version: A special version of Flash Player or Adobe AIR (ADL) that contains code for notifying users of run-time errors. In the standard version of Flash Player or Adobe AIR (the one that most users have), errors that arent handled by your ActionScript code are ignored. In the debugger versions (which are included with Adobe Flash CS3 Professional, Adobe Flex, and Adobe AIR), a warning message appears when an unhandled error happens. Exception: An error that happens while a program is running and that the run-time environment (that is, Flash Player or Adobe AIR) cant resolve on its own.

ADOBE FLEX 3 167

Re-throw: When your code catches an exception, Flash Player and Adobe AIR no longer notify other objects of the exception. If its important for other objects to be notified of the exception, your code must re-throw the exception to start the notification process again. Synchronous: A program command, such as a method call, that provides an immediate result (or immediately throws an error), meaning the response can be used within the same code block. Throw: The act of notifying Flash Player or Adobe AIR (and consequently, notifying other objects and ActionScript code) that an error has occurred is known as throwing an error.

Types of errors

When you develop and run applications, you encounter different types of errors and error terminology. The following list introduces the major error types and terms:

ADOBE FLEX 3 184

function validateData():void { try { var tempXML:XML = XML(xmlText.text); Validator.validateEmployeeXML(tempXML); status.text = "The XML was successfully validated."; } catch (error:FatalError) { showFatalError(error); } catch (error:WarningError) { showWarningError(error); } catch (error:Error) { showGenericError(error); } }
First, a temporary XML object is created using the contents of the TextArea component instance xmlText. Next, the validateEmployeeXML() method in the custom Validator class (com.example.programmingas3/errors/Validator.as) is invoked and passes the temporary XML object as a parameter. If the XML packet is valid, the status Label component instance displays a success message and the application exits. If the validateEmployeeXML() method throws a custom error (that is, a FatalError, WarningError, or a generic Error occurs), the appropriate catch statement executes and calls either the showFatalError(), showWarningError(), or showGenericError() methods. Each of these methods displays an appropriate message in a text area named statusText to notify the user of the specific error that occurred. Each method also updates the status Label component instance with a specific message. If a fatal error occurs during an attempt to validate the employee XML packet, the error message is displayed in the statusText text area, and the xmlText TextArea component instance and validateBtn Button component instance are disabled, as the following code shows:
function showFatalError(error:FatalError):void { var message:String = error.message + "\n\n"; var title:String = error.getTitle(); statusText.text = message + " " + title + "\n\nThis application has ended."; this.xmlText.enabled = false; this.validateBtn.enabled = false; hideButtons(); }
If a warning error instead of a fatal error occurs, the error message is displayed in the statusText TextArea instance, but the xmlText TextField and Button component instances arent disabled. The showWarningError() method displays the custom error message in the statusText text area. The message also asks the user to decide if they want to proceed with validating the XML or abort the script. The following excerpt shows the showWarningError() method:
function showWarningError(error:WarningError):void { var message:String = error.message + "\n\n" + "Do you want to exit this application?"; showButtons(); var title:String = error.getTitle(); statusText.text = message; }

ADOBE FLEX 3 220

<firstName>Chuck</firstName> <position>Jr. data analyst</position> </employee> </employeeList>
The following expressions are all valid:
x.employee.(lastName == "McGee")This is the second employee node. == "McGee").firstNameThis is the firstName property of the second employee
x.employee.(lastName node.
x.employee.(lastName == "McGee").@idThis is the value of the id attribute of the second employee
x.employee.(@id == 347)The first employee node. x.employee.(@id == 347).lastNameThis is the lastName property of the first employee node. x.employee.(@id > 300)This is an XMLList with both employee properties. x.employee.(position.toString().search("analyst") > -1)This is an XMLList with both position
properties. If you try to filter on attributes or elements that may not exist, Flash Player and Adobe AIR will throw an exception. For example, the final line of the following code generates an error, because there is no id attribute in the second p element:
var doc:XML = <body> <p id='123'>Hello, <b>Bob</b>.</p> <p>Hello.</p> </body>; trace(doc.p.(@id == '123'));
Similarly, the final line of following code generates an error because there is no b property of the second p element:
var doc:XML = <body> <p id='123'>Hello, <b>Bob</b>.</p> <p>Hello.</p> </body>; trace(doc.p.(b == 'Bob'));
To avoid these errors, you can identify the properties that have the matching attributes or elements by using the attribute() and elements() methods, as in the following code:
var doc:XML = <body> <p id='123'>Hello, <b>Bob</b>.</p> <p>Hello.</p> </body>; trace(doc.p.(attribute('id') == '123')); trace(doc.p.(elements('b') == 'Bob'));
You can also use the hasOwnProperty() method, as in the following code:
var doc:XML = <body> <p id='123'>Hello, <b>Bob</b>.</p> <p>Hello.</p> </body>; trace(doc.p.(hasOwnProperty('@id') && @id == '123')); trace(doc.p.(hasOwnProperty('b') && b == 'Bob'));

ADOBE FLEX 3 221

Using the for.in and the for each.in statements
ActionScript 3.0 includes the for.in statement and the for each.in statement for iterating through XMLList objects. For example, consider the following XML object, myXML, and the XMLList object, myXML.item. The XMLList object, myXML.item, consists of the two item nodes of the XML object.
var myXML:XML = <order> <item id='1' quantity='2'> <menuName>burger</menuName> <price>3.95</price> </item> <item id='2' quantity='2'> <menuName>fries</menuName> <price>1.45</price> </item> </order>;

In the context of discussing display objects, DisplayObjectContainer objects are also known as display object containers or simply containers. Although all visible display objects inherit from the DisplayObject class, the type of each is of a specific subclass of DisplayObject class. For example, there is a constructor function for the Shape class or the Video class, but there is no constructor function for the DisplayObject class. As noted earlier, the Stage is a display object container.
Common display programming tasks
Since so much of ActionScript programming involves creating and manipulating visual elements, there are numerous tasks that are related to display programming. This chapter describes common tasks that apply to all display objects, including:
Working with the display list and display object containers
Adding display objects to the display list Removing objects from the display list Moving objects among display containers Moving objects in front of or behind other objects
Working with the Stage Setting the frame rate Controlling Stage scaling Working with full-screen mode
Handling display object events Positioning display objects, including creating drag-and-drop interaction

ADOBE FLEX 3 250

Resizing, scaling, and rotating display objects Applying blending modes, color transformations, and transparency to display objects Masking display objects Animating display objects Loading external display content (such as SWF files or images)
Later chapters in this manual describe additional tasks for working with display objects. These tasks include both tasks that apply to any display object and tasks associated with specific types of display objects:
Drawing vector graphics with ActionScript on display objects, described in Using the drawing API on page 294 Applying geometric transformations to display objects, described in Working with geometry on page 307
Applying graphical filter effects such as blur, glow, drop shadow and more to display objects, described in Filtering display objects on page 318
Working with MovieClip-specific characteristics, described in Working with movie clips on page 346 Working with TextField objects, described in Working with text on page 355 Working with bitmap graphics, described in Working with bitmaps on page 377 Working with video elements, described in Working with video on page 397
Alpha: The color value representing the amount of transparency (or more correctly, the amount of opacity) in a color. For example, a color with an alpha channel value of 60% only shows 60% of its full strength, and is 40% transparent. Bitmap graphic: A graphic that is defined in the computer as a grid (rows and columns) of colored pixels. Commonly bitmap graphics include digital photos and similar images. Blending mode: A specification of how the contents of two overlapping images should interact. Commonly an opaque image on top of another image simply blocks the image underneath so that it isnt visible at all; however, different blending modes cause the colors of the images to blend together in different ways so the resulting content is some combination of the two images. Display list: The hierarchy of display objects that will be rendered as visible screen content by Flash Player and AIR. The Stage is the root of the display list, and all the display objects that are attached to the Stage or one of its children form the display list (even if the object isnt actually rendered, for example if its outside the boundaries of the Stage). Display object: An object which represents some type of visual content in Flash Player or AIR. Only display objects can be included in the display list, and all display object classes are subclasses of the DisplayObject class. Display object container: A special type of display object which can contain child display objects in addition to (generally) having its own visual representation. Main class of the SWF file: The class that defines the behavior for the outermost display object in a SWF file, which conceptually is the class for the SWF file itself. For instance, a SWF created in Flash authoring has a main timeline which contains all other timelines; the main class of the SWF file is the class of which the main timeline is an instance.

// This code creates a drag-and-drop interaction using the startDrag() // technique. // square is a DisplayObject (e.g. a MovieClip or Sprite instance). import flash.events.MouseEvent; // This function is called when the mouse button is pressed. function startDragging(event:MouseEvent):void { square.startDrag(); } // This function is called when the mouse button is released. function stopDragging(event:MouseEvent):void { square.stopDrag(); } square.addEventListener(MouseEvent.MOUSE_DOWN, startDragging); square.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
This technique suffers from one fairly significant limitation: only one item at a time can be dragged using startDrag(). If one display object is being dragged and the startDrag() method is called on another display object, the first display object stops following the mouse immediately. For example, if the startDragging() function is changed as shown here, only the circle object will be dragged, in spite of the square.startDrag() method call:

ADOBE FLEX 3 267

function startDragging(event:MouseEvent):void { square.startDrag(); circle.startDrag(); }
As a consequence of the fact that only one object can be dragged at a time using startDrag(), the stopDrag() method can be called on any display object and it stops whatever object is currently being dragged. If you need to drag more than one display object, or to avoid the possibility of conflicts where more than one object might potentially use startDrag(), its best to use the mouse-following technique to create the dragging effect. With this technique, when the mouse button is pressed, a function is subscribed as a listener to the mouseMove event of the Stage. This function, which is then called every time the mouse moves, causes the dragged object to jump to the x, y coordinate of the mouse. Once the mouse button is released, the function is unsubscribed as a listener, meaning it is no longer called when the mouse moves and the object stops following the mouse cursor. Here is some code that demonstrates this technique:

myShape.graphics.beginFill(0x00FF00);
Calling any fill method implicitly ends any previous fill before starting a new one. Calling any method that specifies a stroke style replaces the previous stroke, but does not alter a previously specified fill, and vice versa. Once you have specified the line style and fill properties, the next step is to indicate the starting point for your drawing. The Graphics instance has a drawing point, like the tip of a pen on a piece of paper. Wherever the drawing point is located, that is where the next drawing action will begin. Initially a Graphics object begins with its drawing point at the point 0, 0 in the coordinate space of the object on which its drawing. To start the drawing at a different point, you can first call the moveTo() method before calling one of the drawing methods. This is analogous to lifting the pen tip off of the paper and moving it to a new position. With the drawing point in place you draw using a series of calls to the drawing methods lineTo() (for drawing straight lines) and curveTo() (for drawing curved lines). While you are drawing, you can call the moveTo() method at any time to move the drawing point to a new position without drawing.

ADOBE FLEX 3 297

While drawing, if you have specified a fill color, you can tell Adobe Flash Player or Adobe AIR to close off the fill by calling the endFill() method. If you have not drawn a closed shape (in other words, if at the time you call endFill() the drawing point is not at the starting point of the shape), when you call the endFill() method Flash Player or AIR automatically closes the shape by drawing a straight line from the current drawing point to the location specified in the most recent moveTo() call. If you have started a fill and not called endFill(), calling beginFill() (or one of the other fill methods) closes the current fill and starts the new one.

Drawing straight lines

When you call the lineTo() method, the Graphics object draws a straight line from the current drawing point to the coordinates you specify as the two parameters in the method call, drawing with the line style you have specified. For example, this line of code puts the drawing point at the point 100, 100 then draws a line to the point 200, 200:
myShape.graphics.moveTo(100, 100); myShape.graphics.lineTo(200, 200);
The following example draws red and green triangles with a height of 100 pixels:
var triangleHeight:uint = 100; var triangle:Shape = new Shape(); // red triangle, starting at point 0, 0 triangle.graphics.beginFill(0xFF0000); triangle.graphics.moveTo(triangleHeight/2, 0); triangle.graphics.lineTo(triangleHeight, triangleHeight); triangle.graphics.lineTo(0, triangleHeight); triangle.graphics.lineTo(triangleHeight/2, 0); // green triangle, starting at point 200, 0 triangle.graphics.beginFill(0x00FF00); triangle.graphics.moveTo(200 + triangleHeight/2, 0); triangle.graphics.lineTo(200 + triangleHeight, triangleHeight); triangle.graphics.lineTo(200, triangleHeight); triangle.graphics.lineTo(200 + triangleHeight/2, 0); this.addChild(triangle);

import flash.media.Microphone; var mic:Microphone = Microphone.getMicrophone(); mic.addEventListener(StatusEvent.STATUS, this.onMicStatus); function onMicStatus(event:StatusEvent):void { if (event.code == "Microphone.Unmuted") { trace("Microphone access was allowed."); } else if (event.code == "Microphone.Muted") { trace("Microphone access was denied."); } }
The StatusEvent.code property will contain Microphone.Unmuted if access was allowed, or Microphone.Muted if access was denied. Note: The Microphone.muted property is set to true or false when the user allows or denies microphone access, respectively. However the muted property is not set on the Microphone instance until the StatusEvent has been dispatched, so your application should also wait for the StatusEvent.STATUS event to be dispatched before checking the Microphone.muted property.
Routing microphone audio to local speakers
Audio input from a microphone can be routed to the local system speakers by calling the Microphone.setLoopback() method with a parameter value of true. When sound from a local microphone is routed to local speakers, there is a risk of creating an audio feedback loop, which can cause loud squealing sounds and can potentially damage sound hardware. Calling the Microphone.setUseEchoSuppression() method with a parameter value of true reduces, but does not completely eliminate, the risk that audio feedback will occur. Adobe recommends you always call Microphone.setUseEchoSuppression(true) before calling Microphone.setLoopback(true), unless you are certain that the user is playing back the sound using headphones or something other than speakers. The following code shows how to route the audio from a local microphone to the local system speakers:
var mic:Microphone = Microphone.getMicrophone(); mic.setUseEchoSuppression(true); mic.setLoopBack(true);
Altering microphone audio
Your application can alter the audio data that comes from a microphone in two ways. First, it can change the gain of the input sound, which effectively multiplies the input values by a specified amount to create a louder or quieter sound. The Microphone.gain property accepts numeric values between 0 and 100 inclusive. A value of 50 acts like a multiplier of one and specifies normal volume. A value of zero acts like a multiplier of zero and effectively silences the input audio. Values above 50 specify higher than normal volume.

Common networking and communication tasks
The following list describes the most common things youll want to do related to external communication from ActionScript; these tasks are described in this chapter:
Loading data from an external file or server script Sending data to a server script Communicating with other local SWF files Working with binary socket connections Communicating with XML sockets Storing persistent local data Uploading files to a server Downloading files from a server to the users machine
External data: Data that is stored in some form outside of the SWF file, and loaded into the SWF file when needed. This data could be stored in a file thats loaded directly, or stored in a database or other form that is retrieved by calling scripts or programs running on a server. URL-encoded variables: The URL-encoded format provides a way to represent several variables (pairs of variable names and values) in a single string of text. Individual variables are written in the format name=value. Each variable (that is, each name-value pair) is separated by ampersand characters, like this: variable1=value1&variable2=value2. In this way, an indefinite number of variables can be sent as a single message. MIME type: A standard code used to identify the type of a given file in Internet communication. Any given file type has a specific code that is used to identify it. When sending a file or message, a computer (such as a web server or a users Flash Player or AIR instance) will specify the type of file being sent. HTTP: Hypertext Transfer Protocola standard format for delivering web pages and various other types of content that are sent over the Internet. Request method: When a program such as Flash Player or a web browser sends a message (called an HTTP request) to a web server, any data being sent can be embedded in the request in one of two ways; these are the two request methods GET and POST. On the server end, the program receiving the request will need to look in the appropriate portion of the request to find the data, so the request method used to send data from ActionScript should match the request method used to read that data on the server.
Socket connection: A persistent connection for communication between two computers. Upload: To send a file to another computer. Download: To retrieve a file from another computer.

Using a proxy class to hide the details of the serialized XML format that Flash Player uses for messages sent to an ActiveX container
To get the application files for this sample, see www.adobe.com/go/learn_programmingAS3samples_flash. The Introvert IM C# files can be found in the Samples/IntrovertIM_CSharp folder. The application consists of the following files:
File AppForm.cs bin/Debug/IntrovertIMApp.swf ExternalInterfaceProxy/ExternalInterfaceProxy.cs Description The main application file with the C# Windows Forms interface. The SWF file loaded by the application. The class that serves as a wrapper around the ActiveX control for External Interface communication. It provides mechanisms for calling and receiving calls from ActionScript.

ADOBE FLEX 3 530

File ExternalInterfaceProxy/ExternalInterfaceSerializer.cs ExternalInterfaceProxy/ExternalInterfaceEventArgs.cs
Description The class that performs the task of converting Flash Players XML format messages to.NET objects. This file defines two C# types (classes): a custom delegate, and an event arguments class, which are used by the ExternalInterfaceProxy class to notify a listener of a function call from ActionScript. This class is a value object representing a function call from ActionScript to the ActiveX container, with properties for the function name and parameters. The SWF file loaded by the application. Wrapper assemblies created by Visual Studio.NET that are required to access the Flash Player (Adobe Shockwave Flash) ActiveX control from managed code.
ExternalInterfaceProxy/ExternalInterfaceCall.cs
bin/Debug/IntrovertIMApp.swf obj/AxInterop.ShockwaveFlashObjects.dll, obj/Interop.ShockwaveFlashObjects.dll
Overview of the Introvert IM C# Application
This sample application represents two instant-messaging client programs (one within a SWF file and another built with Windows Forms) that communicate with each other. The user interface includes an instance of the Shockwave Flash ActiveX control, within which the SWF file containing the ActionScript IM client is loaded. The interface also includes several text fields that make up the Windows Forms IM client: a field for entering messages (MessageText), another that displays the transcript of the messages sent between the clients (Transcript), and a third (Status) that displays the availability status as set in the SWF IM client.

ADOBE FLEX 3 533

As this example shows, the ExternalInterfaceProxy classs Call() method is very similar to its ActionScript counterpart, ExternalInterface.Call(). The first parameter is a string, the name of the function to call. Any additional parameters (not shown here) are passed along to the ActionScript function. If the ActionScript function returns a value, that value is returned by the Call() method (as seen in the previous example).
Inside the ExternalInterfaceProxy class
Using a proxy wrapper around the ActiveX control may not always be practical, or you may wish to write your own proxy class (for instance, in a different programming language or targeting a different platform). Although not all the details of creating a proxy will be explained here, it is instructive to understand the inner workings of the proxy class in this example. You use the Shockwave Flash ActiveX controls CallFunction() method to call an ActionScript function from the ActiveX container using the external API. This is shown in this extract from the ExternalInterfaceProxy classs Call() method:
// Call an ActionScript function on the SWF in "_flashControl", // which is a Shockwave Flash ActiveX control. string response = _flashControl.CallFunction(request);
In this code excerpt, _flashControl is the Shockwave Flash ActiveX control. ActionScript function calls are made using the CallFunction() method. That method takes one parameter (request in the example), which is a string containing XML-formatted instructions including the name of the ActionScript function to call and any parameters. Any value returned from ActionScript is encoded as an XML-formatted string and sent back as the return value of the CallFunction() call. In this example, that XML string is stored in the response variable. Receiving a function call from ActionScript is a multistep process. Function calls from ActionScript cause the Shockwave Flash ActiveX control to dispatch its FlashCall event, so a class (such as the ExternalInterfaceProxy class) that intends to receive calls from a SWF file needs to define a handler for that event. In the ExternalInterfaceProxy class, the event handler function is named _flashControl_FlashCall(), and it is registered to listen for the event in the class constructor, as follows:
private AxShockwaveFlash _flashControl; public ExternalInterfaceProxy(AxShockwaveFlash flashControl) { _flashControl = flashControl; _flashControl.FlashCall += new _IShockwaveFlashEvents_FlashCallEventHandler(_flashControl_FlashCall); }. private void _flashControl_FlashCall(object sender, _IShockwaveFlashEvents_FlashCallEvent e) { // Use the event objects request property ("e.request") // to execute some action. // Return a value to ActionScript; // the returned value must first be encoded as an XML-formatted string. _flashControl.SetReturnValue(encodedResponse); }

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

L62640L AVR-1909 Galeo 5850 943NWX TK-T200 Ii-2003 FZ6-N-2004 Macintosh D2424LV CFD758 YP-T7FX 702 SI QHC6501X LP150CED 55C7000 Epiphone W2234S-SN OT-S320 V2020 LA32R71BA SA-W505 WF-T8501TP MKS-100 31L809 Moves VE510S PCG-FX804 KH 2032 Sport ZWG3121 WFF 1101 BD-HP20RU F50872 Venture HC SRE 302 KX-FP151 CDX-MR10 Motorola I580 LS-color Plus MS10AH Nr0 SR-135 NWZ-E344RED W300I DOP740B PRO 4320 SG-9800 Review MX5700D-22S BOX V2 3DE-7985E EDC503M WVC54GC MAX-C550 RM4401 4730Z Mwdgce-25 1 Winter P5LP-LE Hkts 7 32PFL5522D ESD-9000 Lide 70 PHT-300X Urc 4041 TX-SR805 42PFL7403H 10 BH-108 FOB481NC PSR-3000 DC290 Touch 320 7600GT IC-M1 UP-DP10 GT-S3600I 933HD 240V Minimoys Ciclopuls CP29 P330M Flashpaper MVH-8200BT WD-12476BDM 330SI Qtsi HT-DDW870 TD4200 Tektronix 2213 EL-531GH I845GE X3 2004 Extensa 5620 CDE-9845RR Fantom-X MX5100VR-00 Iqzoom 105R CLP-1001 CS-HE9GKE V4 0 JBL CS12 Precision IS8100

 

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