If this guide is distributed with software that includes an end-user agreement, this guide, as well as the software described in it, is
furnished under license and may be used or copied only in accordance with the terms of such license. Except as permitted by any
such license, no part of this guide may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means,
electronic, mechanical, recording, or otherwise, without the prior written permission of Adobe Systems Incorporated. Please note
that the content in this guide is protected under copyright law even if it is not distributed with software that includes an end-user
license agreement.
The content of this guide is furnished for informational use only, is subject to change without notice, and should not be
construed as a commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability
for any errors or inaccuracies that may appear in the informational content contained in this guide.
Please remember that existing artwork or images that you may want to include in your project may be protected under copyright
law. The unauthorized incorporation of such material into your new work could be a violation of the rights of the copyright
owner. Please be sure to obtain any permission required from the copyright owner.
Any references to company names in sample templates are for demonstration purposes only and are not intended to refer to any
actual organization.
Adobe, the Adobe logo, Flex, Flex Builder and Flash Player are either registered trademarks or trademarks of Adobe Systems
Incorporated in the United States and/or other countries. ActiveX and Windows are either registered trademarks or trademarks of
Microsoft Corporation in the United States and other countries. Macintosh is a trademark of Apple Computer, Inc., registered in
the United States and other countries. All other trademarks are the property of their respective owners.
Speech compression and decompression technology licensed from Nellymoser, Inc. (www.nellymoser.com).
Sorenson™ Spark™ video compression and decompression technology licensed from Sorenson Media, Inc.
Adobe Systems Incorporated, 345 Park Avenue, San Jose, California 95110, USA
Notice to U.S. government end users. The software and documentation are “Commercial Items,” as that term is defined at 48
C.F.R. §2.101, consisting of “Commercial Computer Software” and “Commercial Computer Software Documentation,” as such
terms are used in 48 C.F.R. §12.212 or 48 C.F.R. §227.7202, as applicable. Consistent with 48 C.F.R. §12.212 or 48 C.F.R.
§§227.7202-1 through 227.7202-4, as applicable, the Commercial Computer Software and Commercial Computer Software
Documentation are being licensed to U.S. Government end users (a) only as Commercial items and (b) with only those rights as
are granted to all other end users pursuant to the terms and conditions herein. Unpublished-rights reserved under the copyright
laws of the United States. Adobe Systems Incorporated, 345 Park Avenue, San Jose, CA 95110-2704, USA. For U.S.
Government End Users, Adobe agrees to comply with all applicable equal opportunity laws including, if appropriate, the
provisions of Executive Order 11246, as amended, Section 402 of the Vietnam Era Veterans Readjustment Assistance Act of
1974 (38 USC 4212), and Section 503 of the Rehabilitation Act of 1973, as amended, and the regulations at 41 CFR Parts 60-1
through 60-60, 60-250 ,and 60-741. The affirmative action clause and regulations contained in the preceding sentence shall be
incorporated by reference.
This manual provides a foundation for developing applications in ActionScript 3.0. To best
understand the ideas and techniques described, you should already be familiar with general
programming concepts such as data types, variables, loops, and functions. You should also
understand basic object-oriented programming concepts like classes and inheritance. Prior
knowledge of ActionScript 1.0 or ActionScript 2.0 is helpful but not necessary.
Part 2, “Core ActionScript 3.0 Data Types
and Classes”
Part 3, “Flash Player APIs”Describes important features that are
The manual contains numerous sample files for important or commonly used classes to
demonstrate application programming concepts for those APIs. Sample files are packaged in
ways to make them easier to load and use with Adobe® Flex™ Builder 2 and may include
wrapper files. However, the core sample code is pure ActionScript 3.0 that you can use in
whichever development environment you prefer.
ActionScript 3.0 can be written and compiled a number of ways, including:
■ Using the Adobe Flex Builder 2 development environment
■ Using any text editor and a command-line compiler, such as the one provided with Flex
Builder 2
■ Using the Adobe® Flash® CS3 authoring tool from Adobe
For more information about ActionScript development environments, see Chapter 1,
“Introduction to ActionScript 3.0.”
Discusses core ActionScript 3.0 concepts,
including language syntax, statements and
operators, the ECMAScript edition 4 draft
language specification, object-oriented
ActionScript programming, and the new
approach to managing display objects on the
Adobe
® Flash® Player 9 display list.
Describes top-level data types in ActionScript
3.0 that are also part of the ECMAScript draft
specification.
implemented in packages and classes specific to
Adobe Flash Player 9, including event handling,
networking and communications, file input and
output, the external interface, the application
security model, and more.
12About This Manual
To understand the code samples in this manual, you don’t need to have prior experience using
integrated development environments for ActionScript, such as Flex Builder or the Flash
authoring tool. You will, however, want to refer to the documentation for those tools to learn
how to use them to write and compile ActionScript 3.0 code. For more information, see
“Accessing ActionScript documentation” on page 13.
Accessing ActionScript documentation
Because this manual focuses on describing ActionScript 3.0, which is a rich and powerful
object-oriented programming language, it does not extensively cover the application
development process or workflow within a particular tool or server architecture. So in
addition to Programming ActionScript 3.0, you’ll want to consult other sources of
documentation as you design, develop, test, and deploy ActionScript 3.0 applications.
ActionScript 3.0 documentation
This manual familiarizes you with the concepts behind the ActionScript 3.0 programming
language and gives you implementation details and samples illustrating important language
features. However, this manual is not a complete language reference. For that, see the
ActionScript 3.0 Language Reference, which describes every class, method, property, and event
in the language. The ActionScript 3.0 Language Reference provides detailed reference
information about the core language, Flex MXML classes and components (in the mx
packages), and Flash Player APIs (in the flash packages).
Accessing ActionScript documentation13
Flex documentation
If you use the Flex development environment, you may want to consult these manuals:
BookDescription
Flex 2 Developer’s GuideDescribes how to develop your dynamic web
applications.
Getting Started with Flex 2Contains an overview of Flex features and
application development procedures.
Building and Deploying Flex 2 ApplicationsDescribes how to build and deploy Flex
applications.
Creating and Extending Flex 2 Components Describes how to create and extend Flex
components.
Migrating Applications to Flex 2Provides an overview of the migration process,
as well as detailed descriptions of changes in
Flex and ActionScript.
Using Flex Builder 2Contains comprehensive information about all
Flex Builder features, for every level of Flex
Builder users.
ActionScript 3.0 Language ReferenceProvides descriptions, syntax, usage, and code
examples for the Flex API.
Developer Center
The Adobe Developer Center is a your resource for up-to-the-minute information on
ActionScript, articles about real-world application development, and information about
important emerging issues. View the Developer Center at www.adobe.com/devnet/.
14About This Manual
CHAPTER 1
Introduction to
ActionScript 3.0
This chapter provides an overview of ActionScript 3.0, the newest and most revolutionary
version of ActionScript.
ActionScript is the programming language for the Flash Player run-time environment. It
enables interactivity, data handling, and much more in Flash content and applications.
ActionScript is executed by the ActionScript Virtual Machine, which is part of Flash Player.
ActionScript code is typically compiled into bytecode format by a compiler, such as the one
built into the Flash authoring tool or Flex Builder, or that is available in the Flex SDK and the
Flex Data Services. The bytecode is embedded in SWF files, which are executed by the Flash
Player, the run-time environment.
ActionScript 3.0 offers a robust programming model that will be familiar to developers with a
basic knowledge of object-oriented programming. Some of the key features of ActionScript
3.0 include the following:
■ A new ActionScript Virtual Machine, called AVM2, that uses a new bytecode instruction
set and provides significant performance improvements
■ A more modern compiler code base that adheres much more closely to the ECMAScript
(ECMA 262) standard and that performs deeper optimizations than previous versions of
the compiler
■ An expanded and improved application programming interface (API), with low-level
control of objects and a true object-oriented model
1
15
■ A core language based on the upcoming ECMAScript (ECMA-262) edition 4 draft
language specification
■ An XML API based on ECMAScript for XML (E4X), as specified in ECMA-357 edition
2 specification. E4X is a language extension to ECMAScript that adds XML as a native
data type of the language.
■ An event model based on the Document Object Model (DOM) Level 3 Events
Specification
Advantages of ActionScript 3.0
ActionScript 3.0 goes beyond the scripting capabilities of previous versions of ActionScript. It
is designed to facilitate the creation of highly complex applications with large data sets and
object-oriented, reusable code bases. While ActionScript 3.0 is not required for content that
runs in Adobe Flash Player 9, it opens the door to performance improvements that are only
available with the AVM2, the new virtual machine. ActionScript 3.0 code can execute up to
ten times faster than legacy ActionScript code.
The older version of ActionScript Virtual Machine, AVM1, executes ActionScript 1.0 and
ActionScript 2.0 code. AVM1 is supported by Flash Player 9 for backward compatibility with
existing and legacy content. For more information, see “Compatibility with previous versions”
on page 20.
What’s new in ActionScript 3.0
Although ActionScript 3.0 contains many classes and features that will be familiar to
ActionScript programmers, ActionScript 3.0 is architecturally and conceptually different from
previous versions of ActionScript. The enhancements in ActionScript 3.0 include new
features of the core language and an improved Flash Player API that provides increased
control of low-level objects.
Core language features
The core language defines the basic building blocks of the programming language, such as
statements, expressions, conditions, loops, and types. ActionScript 3.0 contains many new
features that speed up the development process.
16Introduction to ActionScript 3.0
Run-time exceptions
ActionScript 3.0 reports more error conditions than previous versions of ActionScript. Runtime exceptions are used for common error conditions, improving the debugging experience
and enabling you to develop applications that handle errors robustly. Run-time errors can
provide stack traces annotated with source file and line number information, helping you
quickly pinpoint errors.
Run-time types
In ActionScript 2.0, type annotations were primarily a developer aid; at run time, all values
were dynamically typed. In ActionScript 3.0, type information is preserved at run time, and
used for a number of purposes. Flash Player 9 performs run-time type checking, improving
the system’s type safety. Type information is also used to represent variables in native machine
representations, improving performance and reducing memory usage.
Sealed classes
ActionScript 3.0 introduces the concept of sealed classes. A sealed class possesses only the
fixed set of properties and methods that were defined at compile time; additional properties
and methods cannot be added. This enables stricter compile-time checking, resulting in more
robust programs. It also improves memory usage by not requiring an internal hash table for
each object instance. Dynamic classes are also possible using the
in ActionScript 3.0 are sealed by default, but can be declared to be dynamic with the
keyword.
dynamic keyword. All classes
dynamic
Method closures
ActionScript 3.0 enables a method closure to automatically remember its original object
instance. This feature is useful for event handling. In ActionScript 2.0, method closures
would not remember what object instance they were extracted from, leading to unexpected
behavior when the method closure was invoked. The mx.utils.Delegate class was a popular
workaround, but it is no longer needed.
What’s new in ActionScript 3.017
ECMAScript for XML (E4X)
ActionScript 3.0 implements ECMAScript for XML (E4X), recently standardized as ECMA-
357. E4X offers a natural, fluent set of language constructs for manipulating XML. In
contrast to traditional XML-parsing APIs, XML with E4X performs like a native data type of
the language. E4X streamlines the development of applications that manipulate XML by
drastically reducing the amount of code needed. For more information about the ActionScript
3.0 implementation of E4X, see Chapter 11, “Working with XML,” on page 311.
To view ECMA’s E4X specification, go to www.ecma-international.org/publications/files/
ECMA-ST/ECMA-357.pdf .
Regular expressions
ActionScript 3.0 includes native support for regular expressions so that you can quickly search
for and manipulate strings. ActionScript 3.0 implements support for regular expressions as
they are defined in the ECMAScript edition 3 language specification (ECMA-262).
Namespaces
Namespaces are similar to the traditional access specifiers used to control visibility of
declarations (
can have names of your choice. Namespaces are outfitted with a Universal Resource Identifier
(URI) to avoid collisions, and are also used to represent XML namespaces when you work
with E4X.
public, private, protected). They work as custom access specifiers, which
New primitive types
ActionScript 2.0 has a single numeric type, Number, a double-precision, floating point
number. ActionScript 3.0 contains the int and uint types. The int type is a 32-bit signed
integer that lets ActionScript code take advantage of the fast integer math capabilities of the
CPU. The int type is useful for loop counters and variables where integers are used. The uint
type is an unsigned, 32-bit integer type that is useful for RGB color values, byte counts, and
more.
Flash Player API features
The Flash Player API in ActionScript 3.0 contains many new classes that allow you to control
objects at a low level. The architecture of the language is completely new and more intuitive.
While there are too many new classes to cover in detail here, the following sections highlight
some significant changes.
18Introduction to ActionScript 3.0
DOM3 event model
Document Object Model Level 3 event model (DOM3) provides a standard way of
generating and handling event messages so that objects within applications can interact and
communicate, maintaining their state and responding to change. Patterned after the World
Wide Web Consortium DOM Level 3 Events Specification, this model provides a clearer and
more efficient mechanism than the event systems available in previous versions of
ActionScript.
Events and error events are located in the flash.events package. The Flex application
framework uses the same event model as the Flash Player API, so the event system is unified
across the Flash platform.
Display list API
The API for accessing the Flash Player display list—the tree that contains any visual elements
in a Flash application—consists of classes for working with visual primitives in Flash.
The new Sprite class is a lightweight building block, similar to MovieClip but more
appropriate as a base class for UI components. The new Shape class represents raw vector
shapes. These classes can be instantiated naturally with the
dynamically re-parented at any time.
Depth management is now automatic and built into Flash Player, rendering assignment of
depth numbers unnecessary. New methods are provided for specifying and managing the zorder of objects.
new operator and can be
Handling dynamic data and content
ActionScript 3.0 contains mechanisms for loading and handling assets and data in your Flash
application that are intuitive and consistent across the API. The new Loader class provides a
single mechanism for loading SWF files and image assets and provides a way to access detailed
information about loaded content. The URLLoader
loading text and binary data in data-driven applications. The Socket class provides a means to
read and write binary data to server sockets in any format.
class provides a separate mechanism for
What’s new in ActionScript 3.019
Low-level data access
Various APIs provide low-level access to data that was never before available in ActionScript.
For data that is being downloaded, the URLStream class, which is implemented by
URLLoader, provides access to data as raw binary data while it is being downloaded. The
ByteArray class lets you optimize reading, writing, and working with binary data. The new
Sound API provides detailed control of sound through the SoundChannel and SoundMixer
classes. New APIs dealing with security provide information about the security privileges of a
SWF or loaded content, enabling you to better handle security errors.
Working with text
ActionScript 3.0 contains a flash.text package for all text-related APIs. The TextLineMetrics
class provides detailed metrics for a line of text within a text field; it replaces the
TextField.getLineMetrics() method in ActionScript 2.0. The TextField class contains a
number of interesting new low-level methods that can provide specific information about a
line of text or a single character in a text field. These methods include
getCharBoundaries(), which returns a rectangle representing the bounding box of a
character,
point, and
paragraph. Line-level methods include
characters in a specified line of text, and
specified line. A new Font class provides a means to manage embedded fonts in SWF files.
getCharIndexAtPoint(), which returns the index of the character at a specified
getFirstCharInParagraph(), which returns the index of the first character in a
getLineLength(), which returns the number of
getLineText(), which returns the text of the
Compatibility with previous versions
As always, Flash Player provides full backward compatibility with previously published
content. Any content that ran in previous versions of Flash Player runs in Flash Player 9. The
introduction of ActionScript 3.0 in Flash Player 9, however, does present some challenges for
interoperability between old and new content running in Flash Player 9. The compatibility
issues include the following:
■ A single SWF file cannot combine ActionScript 1.0 or 2.0 code with ActionScript 3.0
code.
■ ActionScript 3.0 code can load a SWF file written in ActionScript 1.0 or 2.0, but it
cannot access the SWF file’s variables and functions.
■ SWF files written in ActionScript 1.0 or 2.0 cannot load SWF files written in
ActionScript 3.0. This means that SWF files authored in Flash 8 or Flex Builder 1.5 or
earlier versions cannot load ActionScript 3.0 SWF files.
20Introduction to ActionScript 3.0
The only exception to this rule is that an ActionScript 2.0 SWF file can replace itself with
an ActionScript 3.0 SWF file, as long as the ActionScript 2.0 SWF file hasn't previously
loaded anything into any of its levels. An ActionScript 2.0 SWF file can do this through a
call to
loadMovieNum(), passing a value of 0 to the level parameter.
■ In general, SWF files written in ActionScript 1.0 or 2.0 must be migrated if they are to
work together with SWF files written in ActionScript 3.0. For example, say you created a
media player using ActionScript 2.0. The media player loads various content that was also
created using ActionScript 2.0. You cannot create new content in ActionScript 3.0 and
load it in the media player. You must migrate the video player to ActionScript 3.0.
If, however, you create a media player in ActionScript 3.0, that media player can perform
simple loads of your ActionScript 2.0 content.
The following diagram summarizes the limitations of previous versions of Flash Player in
relation to loading new content and executing code, as well as the limitations for crossscripting between SWF files written in different versions of ActionScript.
Supported
Run-time environment
functionality
Flash Player 7Flash Player 8Flash Player 9
Can load SWFs
published for
Contains this AVM
Runs SWFs written in
ActionScript
Supported
7 and earlier8 and earlier9 and earlier
AVM1AVM1AVM1 and AVM2
1.0 and 2.01.0 and 2.01.0 and 2.0, and 3.0
Content created in
functionality*
ActionScript 1.0 and 2.0ActionScript 3.0
Can load content and
execute code in content
created in
Can cross script content
created in
* Content running in Flash Player 9 or later. Content running in Flash Player 8 or earlier can
load, display, execute, and cross-script only ActionScript 1.0 and 2.0.
†ActionScript 3.0 through Local Connection.
‡ActionScript 1.0 and 2.0 through LocalConnection.
ActionScript 1.0 and 2.0 onlyActionScript 1.0 and 2.0,
and ActionScript 3.0
ActionScript 1.0 and 2.0 only†
ActionScript 3.0‡
Compatibility with previous versions21
22Introduction to ActionScript 3.0
CHAPTER 2
Getting Started with
ActionScript
This chapter provides a no-frills, step-by-step approach to building a simple ActionScript 3.0
application.
The ActionScript 3.0 programming language can be used from within a number of different
development environments, including Macromedia Flash from Adobe and Adobe Flex
Builder 2. This chapter will show how to create modular ActionScript code that can be used
from within either of these application development environments.
No matter whether your ActionScript project is large or small, using a process to design and
develop your application will help you work more efficiently and effectively. Here are a set of
steps for a basic development process for building an application that uses ActionScript 3.0:
1. Design your application.
You should describe your application in some way before you start building it.
2. Compose your ActionScript 3.0 code.
You can create ActionScript code using Flash, Flex Builder, Macromedia Dreamweaver®
from Adobe, or a text editor.
23
3. Create a Flash or Flex application file to run your code.
In the Flash authoring tool, this involves creating a new FLA file, setting up the publish
settings, adding user interface components to the application, and referencing the
ActionScript code. In the Flex development environment, creating a new application file
involves defining the application and adding user interface components using MXML,
and referencing the ActionScript code.
4. Publish and test your ActionScript application.
This involves running your application from within the Flash authoring or Flex
development environment, and making sure it does everything you intended.
Note that you don’t necessarily have to follow these steps in order, or completely finish one
step before working on another. For example, you might design one screen of your application
(step 1), then create the graphics, buttons, and so forth (step 3), before writing ActionScript
code (step 2) and testing (step 4). Or you might design part of it, then add one button or
interface element at a time, writing ActionScript for each one and testing it as it’s built. So
while it’s convenient to remember these four stages of the development process, in real-world
development it’s usually more effective to move back and forth among the stages as
appropriate.
Options for organizing your code
You can use ActionScript 3.0 code to power everything from simple graphics animations to
complex, client-server transaction processing systems. Depending on the type of application
you’re building, you may prefer to use one or more of these different ways of including
ActionScript in your project.
Storing code in frames in a Flash timeline
In the Flash authoring environment, you can add ActionScript code to any frame in a
timeline. This code will be executed while the movie is playing back, when the playhead
enters that frame.
Placing ActionScript code in frames provides a simple way to add behaviors to applications
built in the Flash authoring tool. You can add code to any frame in the main timeline or to
any frame in the timeline of any MovieClip symbol. However, this flexibility comes with a
cost. When you build larger applications, it becomes easy to lose track of which frames
contain which scripts, which can make the application more difficult to maintain over time.
24Getting Started with ActionScript
Many developers simplify the organization of their ActionScript code in the Flash authoring
tool by placing code only in the first frame of a timeline, or on a specific layer in the Flash
document. This makes it easier to locate and maintain the code in your Flash FLA files.
However, in order to use the same code in another Flash or Flex project, you must copy and
paste the code into the new file.
If you want to be able to use your ActionScript code in other Flash or Flex projects in the
future, you will want to store your code in external ActionScript files (text files with the .as
extension).
Embedding code in Flex MXML files
In a Flex development environment, you can include ActionScript code inside an
<mx:Script> tag in a Flex MXML file. Inline ActionScript code like this has the same
drawback as code placed on a frame in Flash: you cannot reuse the code without cutting and
pasting it to a new source location.
NOTE
You can specify a source parameter for an <mx:Script> tag, which lets you insert
ActionScript code as if it was typed directly within the
source file that you use cannot define its own class, which limits its reusability.
<mx:Script> tag. However, the
Storing code in ActionScript files
If your project involves significant ActionScript code, the best way to organize your code is in
separate ActionScript source files (text files with the .as extension). An ActionScript file can be
structured in one of two ways, depending on how you intend to use it in your application:
■ Unstructured ActionScript code: lines of ActionScript code, including statements or
function definitions, written as though they were entered directly in a timeline script,
MXML file, etc.
ActionScript written in this way can be accessed using the
ActionScript, or the
<mx:Script> tag in Flex MXML. The ActionScript include
statement causes the contents of an external ActionScript file to be inserted at a specific
location and within a given scope in a script, as if it were entered there directly. In the Flex
MXML language, the
<mx:Script> tag lets you specify a source attribute that identifies
an external ActionScript file to be loaded at that point in the application. For example, the
following tag will load an external ActionScript file named Box.as:
<mx:Script source=“Box.as” />
include statement in
Options for organizing your code25
■ ActionScript class definition: a definition of an ActionScript class, including its method
and property definitions.
When you define a class, you can access the ActionScript code in the class by creating an
instance of the class and using its properties, methods, and events, just as you would with
any of the built-in ActionScript classes. This requires two parts:
■Use the import statement to specify the full name of the class, so the ActionScript
compiler knows where to find it. For example, if you want to use the MovieClip class
in ActionScript, you first need to import that class using its full name, including
package and class:
import flash.display.MovieClip;
Alternatively, you can import the package that contains the MovieClip class, which is
equivalent to writing separate import statements for each class in the package:
import flash.display.*;
The only exceptions to the rule that a class must be imported in order to refer to that
class in your code are the top-level classes which are not defined in a package.
■Write code which specifically refers to the class name (usually declaring a variable with
that class as its data type, and creating an instance of the class to store in the variable).
By referring to another class name in ActionScript code, you tell the compiler to load
the definition of that class. For example, given an external class called Box, this
statement causes a new instance of the Box class to be created:
var smallBox:Box = new Box(10,20);
When the compiler comes across the reference to the Box class for the first time, it
searches the loaded source code to locate the Box class definition.
Example: Creating a basic application
You can create external ActionScript source files with an .as extension using Flash, Flex
Builder, Dreamweaver, or any text editor.
ActionScript 3.0 can be used within a number of application development environments,
including the Flash authoring and Flex Builder tools.
This section walks through the steps in creating and enhancing a simple ActionScript 3.0
application using the Flash authoring tool or the Flex Builder 2 tool. The application you’ll
build presents a simple pattern for using external ActionScript 3.0 class files in Flash and Flex
applications. That pattern will apply to all of the other example applications in this book.
26Getting Started with ActionScript
Designing your ActionScript application
You should have some idea about the application you want to build before you start building it.
The representation of your design can be as simple as the name of the application and a brief
statement of its purpose, or as complicated as a set of requirements documents containing
numerous Unified Modeling Language (UML) diagrams. This book doesn’t discuss the
discipline of software design in detail, but it’s important to keep in mind that application
design is an essential step in the development of ActionScript applications.
Our first example of an ActionScript application will be a standard “Hello World”
application, so its design is very simple:
■ The application will be called HelloWorld.
■ It will display a single text field containing the words “Hello World!”
■ In order to be easily reused, it will use a single object-oriented class, named Greeter, which
can be used from within a Flash document or a Flex application.
■ After you create a basic version of the application, you will add new functionality to have
the user enter a user name and have the application check the name against a list of known
users.
With that concise definition in place, you can start building the application itself.
Creating the HelloWorld project and the Greeter class
The design statement for the Hello World application said that its code should be easy to
reuse. With this goal in mind, the application uses a single object-oriented class, named
Greeter, which is used from within an application that you create in Flex Builder or the Flash
authoring tool.
To create the HelloWorld project and Greeter class in Flex Builder:
1. In Flex Builder, select File > New> Flex Project,
2. If the New Flex Project dialog box asks you to select a Flex Server Technology, select Basic,
and then click Next.
3. Type HelloWorld as the Project Name, and then click Finish.
Your new project will be created and should be showing in the Navigator panel. By default
the project should already contain a file named HelloWorld.mxml, and that file should be
open in the Editor panel.
4. Now to create a custom ActionScript class file in the Flex Builder tool, select File > New >
ActionScript File.
Example: Creating a basic application27
5. In the New ActionScript File dialog box, select HelloWorld as the parent folder, type
Greeter.as the filename, and then click Finish.
A new ActionScript editing window is displayed.
Continue with “Adding code to the Greeter class” on page 28.
Adding code to the Greeter class
The Greeter class defines an object, Greeter, that you will be able to use in your HelloWorld
application.
To add code to the Greeter class:
1. Type the following code into the new file:
package
{
public class Greeter
{
public function sayHello():String
{
var greeting:String;
greeting = "Hello World!";
return greeting;
}
}
}
The Greeter class includes a single sayHello() method, which returns a string that says
“Hello” to the user name that is given.
2. Select File > Save to save this ActionScript file.
The Greeter class is now ready to be used in a Flash or Flex application.
Creating an application that uses your ActionScript
code
The Greeter class that you have built defines a self-contained set of software functions, but it
does not represent a complete application. To use the class, you need to create a Flash
document or Flex application.
The HelloWorld application creates an new instance of the Greeter class. Here’s how to attach
the Greeter class to your application.
28Getting Started with ActionScript
To create an ActionScript application using Flex Builder:
1. Open the HelloWorld.mxml file, and type the following code:
// says hello at the start, and asks for the user's name
mainTxt.text = myGreeter.sayHello();
}
]]>
</mx:Script>
<mx:TextArea id = "mainTxt" width="400" />
</mx:Application>
This Flex project includes three MXML tags:
■An <mx:Application> tag, which defines the Application container
■An <mx:Script> tag that includes some ActionScript code
■An <mx:TextArea> tag, which defines a field to display text messages to the user
The code in the
application loads. The
the “Hello World!” string returned by the
<mx:Script> tag defines a initApp() method that is called when the
initApp() method sets the text value of the mainTxt TextArea t o
sayHello() method of the custom class
Greeter, which you just wrote.
2. Select File > Save to save the application.
Continue with “Publishing and testing your ActionScript application” on page 30.
Example: Creating a basic application29
Publishing and testing your ActionScript application
Software development is an iterative process. You write some code, try to compile it, and edit
the code until it compiles cleanly. You run the compiled application, test it to see if it fulfills
the intended design, and if it doesn’t, you edit the code again until it does. The Flash and Flex
Builder development environments offer a number of ways to publish, test, and debug your
applications.
Here are the basic steps for testing the HelloWorld application in each environment.
To publish and test an ActionScript application using Flex Builder:
1. Select Run > Run. Make sure that the Project field shows “HelloWorld” and the
Application file field shows “HelloWorld.mxml”.
2. In the Run dialog box, click Run.
The HelloWorld application starts.
■If any errors or warnings are displayed in the Output window when you test your
application, fix the causes of these errors in the HelloWorld.mxml or Greeter.as files,
and then try testing the application again.
■If there are no compilation errors, a browser window opens showing the Hello World
application. The text “Hello World!” should be displayed.
You have just created a simple but complete object-oriented application that uses ActionScript
3.0. Continue with “Enhancing the HelloWorld application” on page 30.
Enhancing the HelloWorld application
To make the application a little more interesting, you’ll now make it ask for and validate a user
name against a predefined list of names.
First, you will update the Greeter class to add new functionality. Then you will update the
Flex or Flash application to use the new functionality.
To update the Greeter.as file:
1. Open the Greeter.as file.
30Getting Started with ActionScript
Loading...
+ 494 hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.