You are on page 1of 84

Basic Scripting and Interactivity

2014 Aptech Limited


All rights reserved.
No part of this book may be reproduced or copied in any form or by any means graphic, electronic
or mechanical, including photocopying, recording, taping, or storing in information retrieval system or
sent or transferred without the prior written permission of copyright owner Aptech Limited.

All trademarks acknowledged.


APTECH LIMITED
Head Office:
Aptech House,
A-65, MIDC,
Marol, Andheri (East),
Mumbai - 400 093, India.
www.aptech-worldwide.com
E-mail: customercare@aptech.ac.in
Edition 1 February 2014

Preface
Adobe Flash CS3 is a revolutionary program used to create presentations, applications, and other
content that enables user interaction. ActionScript 3.0 language is used to add interactivity to Flash
applications.
The Scripting with Flash book is designed to introduce students to Flash ActionScript 3.0. Using this
book, the students can learn the basic elements of ActionScript 3.0. They will also learn to create
variables and functions, and use ActionScript to control properties and methods of movie clip. The
book also describes the various data types and pre-built components that are used to enhance Flash
projects and debug code.
The ARENA Design team has designed this course keeping in mind that motivation coupled with
relevant training and methodology can bring out the best. The team will be glad to receive your
feedback, suggestions, and recommendations for improvement of the book.
Please feel free to send your feedback to the ARENA Design team at the Head Office, Mumbai.
(Feedback form is attached at the end of the book.)

ARENA Design Team

Table of Contents
Introduction to ActionScript 3.0 and Programming Concept.
Introduction and Programming Fundamentals
Use of Action Panel
Using Trace and Comments
Basic Programming Concepts
Controlling Movie Clips
Basic Event Handling
Data Types
Array
String
Summary
Exercise

Working with Built-in Classes


Conditions and Loops
Working with Movie Clips
Working with Text Fields
Use of Date and Time
Working with Shared Objects
Loading External Files
Summary
Exercise
Object-Oriented Programming with ActionScript 3.0.
Object-Oriented Concept
Classes and Packages
Writing Class
Using Attributes to Class and its Methods and Properties
Creating Object Instances
Setting Classpath
Inheritance Concept
Encapsulation and Polymorphism
Attaching Class to Movie Clip Symbol
Summary
Exercise

Components
Capturing User Inputs
Controlling Mouse
Working with Clips
Using Components
Summary
Exercise
Answer Key

Iconography

: System Requirements

: Note
: Quick Test
: Quick Answers
: Exercise Answers

Se ssi on 1

Introduction to ActionScript 3.0 and


Programming Concept
Learning Outcomes
In this session, you will learn to:

Describe the history of ActionScript


Use Actions panel
Use the Movie Explorer
Apply trace command
Use comments
Use variables, operators, and functions
Describe the various public methods
Control a movie clip using the play() and stop() methods
Describe the various mouse events
Describe data types
Describe the Object data type
Create an array
Add elements to an array
Search for matching elements in an array
Convert an array to a string
Use the concat() method
Use quotes or apostrophes within a string value
Add whitespace characters

Convert string into another type

System Requirements
Windows Operating System
Windows Operating System
Intel Pentium 4 or AMD Athlon 64 processor
Microsoft Windows XP with Service Pack 3 or Windows 7 with Service Pack 1
2 GB of RAM (3 GB recommended)
3.5 GB of available hard-disk
Java Runtime Environment 1.6
Graphics card with at least 64 MB of VRAM
QuickTime 7.6.6 software required for multimedia features
1024768 display (1280800 recommended)
ActionScript is the programming language used for controlling Flash movies and applications. Using
ActionScript, you can create actions to display data on any application. You can also create complex
interactivity in the application and control its playback. While scripting, it is not necessary to
understand every ActionScript element. Using simple actions, you can create scripts.
ActionScript can be added to your application by using the Actions panel, Script window, or any other
external editor. It contains reserved keywords and follows its own rule of syntax.

In ActionScript, variables are used to store and retrieve information. It contains a large library of builtin classes that allow you to create objects to perform many useful tasks. ActionScript is similar to
JavaScript and both are rooted in ECMA-262 standard. It is an international standard for ECMAScript
scripting language.
In this session, you will learn about the programming fundamentals and the basic programming
concept. You will also become familiar with the different data types used.

1.1 Introduction and Programming Fundamentals


An understanding of the working of a computer is essential before using ActionScript. A computer
program is a series of instructions and steps that are executed using a computer. Information or data
is processed or manipulated based on these instructions and the result is generated as an output of
the computer program. Now, this processed data is stored in the computer memory.
Every step in a computer program is in the form of a statement. Similarly, in ActionScript, subsequent
topics contain such statements ending with a semicolon.
Now, for example, if you write a program to move the position of a square image drawn on the screen,
the program should include steps to change the x and y coordinates of the square. The computer then
interprets the inputs provided in the steps and uses this data to move the square to an appropriate
location. In other words, the computer uses the data provided in the program to change the data
stored in the memory. Similarly, you can retrieve other information related to the square image.

History of ActionScript
ActionScript was used as a scripting language for Macromedia Flash authoring tool. Flash was
developed by Macromedia. In 2005, Adobe took over Macromedia and thus, Flash was owned by
Adobe. The first three versions of Macromedia Flash authoring tool provided limited interactivity
features. Earlier, Flash developers used to attach a simple action command to a button or a
frame. The set of actions were limited to basic navigation controls, with commands such as play,
stop, get URL, and goto and play.
In Flash 4.0, these simple set of commands are changed to small scripting languages. New
capabilities introduced for Flash 4, included variables, expressions, operators, if statements, and
loops.
ActionScript 2.0 is simpler to learn than ActionScript 3.0. Although Flash Player runs compiled
ActionScript 2.0 code slower than compiled ActionScript 3.0 code, ActionScript 2.0 is still useful for
many kinds of projects.
The earlier versions of ActionScript Virtual Machine (AVM) used ActionScript 1.0 and ActionScript
2.0 code. Flash Player 9.0 supports AVM1 for backward compatibility with existing and legacy
content. Flash supports more than one version of ActionScript. Therefore, it enables you to fulfill
various requirements of the developers.

1.2 Use of Action Panel


Using the Actions panel, you can create and edit ActionScript code for an object or a frame. The
Actions panel becomes active when a frame, button, or a movie clip instance is selected. The title of
the Actions panel changes depending on the selection. You can create scripts in an .fla file by
entering ActionScript directly into the Actions panel.

To display the Actions panel, on the Windows menu, click Actions or press the F9 key. The
Actions panel, as shown in Figure 1.1, will be displayed.

Figure 1.1: Actions panel

Actions Toolbox
All the elements in this toolbox are categorized. You can access the elements using the
alphabetical index. When you double-click on any element from the categories, it is added to
the Script pane. You can also add an ActionScript element into the Script pane by dragging it
directly to the Script pane.

Script Navigator
Using this navigator, you can quickly swap between the scripts in a Flash document. When you
click any item in the Script navigator, the script related to that item is displayed in the Script
pane and the playhead moves to that position on the Timeline. If you double-click an item in the
Script navigator, the script is pinned.

Script Pane
The Script pane is used to enter the code. You can write the ActionScript directly into the
Script pane, but to reduce the amount of typing, you can also select or drag the actions from
the Actions toolbox to the Script pane. You can also use the Add (+) button to add scripts in
the Script pane.
In the Actions panel, you can drag the vertical bar between the Actions toolbox and Script
pane and resize them. If you double-click the vertical bar, the Actions toolbox will be hidden.
To display it again, double-click the bar. When the Actions toolbox is hidden, you can access
the items available in it using the Add (+) button. You can expand or collapse the Actions
toolbox by clicking the arrow on the vertical bar. You can click the Show/Hide Toolbox button ,
at the top of the Actions panel, to hide or view the ActionScript toolbox.

Using the Movie Explorer


Movie Explorer is a panel that displays all the items of the movie, as well as the movie
structure. This panel can be used to search any particular item or to see an items relationship
with other items in the movie. It contains a list, which displays all currently used items, arranged
in a hierarchical tree.
To access the Movie Explorer, on the Windows menu, click Movie Explorer. The Movie
Explorer panel, as shown in Figure 1.2, will be displayed.

Figure 1.2: Movie Explorer


You can filter the items displayed in the list using the various Show buttons.

1.3 Using Trace and Commands


The trace() statement is similar to the JavaScript alert statement. It sends specific information to
the Output panel. For example, while testing a SWF file, results can be sent to the Output panel,
trace("Hello! Everyone");
While using trace() statement, expressions can be used as parameters. The value of an
expression appears in the Output panel in the test environment.

Applying Trace Command


To apply the trace command, open a fresh Flash document and on the first frame enter the
code in Actions panel. For example,

var james = 5;
var smith = 4;
trace(james);
The output for this piece of code is 5.

Note
The Flash developer can only debug errors that appear in the code. The user can view the
contents of the Output window.
Now, if the trace() statement code is modified to,
trace(james+smith);
The output of the program will be 9. The values assigned to both the variables, James and smith
are added and their sum is displayed in the Output window.

Using comments
Using comments, you can temporarily deactivate a part of the code. By doing this, you can check
the functionality of the various parts of the Flash movie. Comment lines can also be added in the
code in order to explain what it does. Thus, you can comment a code without deleting it for the
future use.
To comment a single line in the code, use two forward slashes (//) in front of the line. For
example,

var james = 5;
//var smith = 4;
trace(james);
To comment multiple lines of code, use a forward slash (/) followed by an asterisk (*) in front of
the first line and asterisk followed by a forward slash at the end of the last line. For example,
/*var james = 5;
var smith = 4;
trace(james);*/
When codes cross more than 100 lines, comments are the best way to write some explanations
that will help you when you return to your code a couple of months later.
For detailed step-by-step procedure, refer demo Using Trace and Comments from:
eResources 4 Me>> My Varsity>> Basic Scripting and Interactivity>> Show Me How

Quick Test 1.1


1. The ____________ panel allows you to create and edit ActionScript code for an object
or a frame.
Output

Actions

Script

None of these

2. The Script Navigator displays all the items of the movie, as well as the movie
structure.
True

False

3. The ____________ statement is similar to the JavaScript alert statement.


show()

hide()

display()

trace()

1.4 Basic Programming Concepts


Modifying the information available in the computer memory involves basic programming. It is
essential to appropriately represent this information in the program. You can do this using the basic
programming concepts, such as variables, operators, and functions.

1.4.1 Variables
Variables can be a representation of numbers, string of characters, or some other values. It can be
considered as a container that is used to store information. In ActionScript, the information stored in
variables are known as objects till the program is running. Variables are the important elements and
are used in nearly every aspect of programming.
Now, consider you have two variables, value1 and value2, and each of these variables have a
value assigned to them. You need to add these two numbers. Therefore, the code will be,
value1 + value2;
Now, the output displayed will be the sum of the values stored in these variables.
In ActionScript, a variable should consist of a variable name, the type of data that can be stored in the
variable, and the actual value stored in the computers memory.
While declaring a variable in ActionScript, it is necessary to specify its data type. Once the data type
is specified, the variable will store information or value related to that data type and will not accept any
other type of data. You can also manipulate or modify the value in the variable by using the
characteristics associated with the data type.

Creating or Declaring a Variable


In ActionScript, a variable can be declared or created using the var statement. For example, to
declare the variable value1, the syntax will be as follows:
var value1:Number;
In this syntax, the data type of value1 is Number, as defined in ActionScript. Thus, the variable
can only store values pertaining to Number data type.
You can also assign values to the variable at the time of declaration. For example, if you want to
assign the value 20 to the variable value1, then the syntax will be,
var value1:Number = 20;
Using Adode Flash CS3 Professional, you can declare a variable by defining the name of the
instance in the Property Inspector. This instance name will be used as the variable name in
Flash. Thus, this instance name or the variable name can be used in ActionScript whenever you
refer to that item.
For example, if a movie clip is placed in the work area and named sampleMC, then the variable
name will be sampleMC and can be used while coding in ActionScript. Therefore, whenever this
variable is modified, the movie clip is modified.

1.4.2 Operators
Operators are built-in functions like commands that operate on one or more values. Unlike functions,
operators do not need parentheses to function.
While processing the program, certain mathematical operators are processed first due to the laws of
arithmetic. In general, complex operations will be executed first followed by simpler operations. Thus,
operators follow a certain order of operations.
In ActionScript, operations are executed in the following order:

Expressions within the parentheses are executed first, starting from the complex to simpler
operation. Parentheses can be used to group expressions that have to be evaluated first.

The results of the functions are evaluated assuming all their arguments are evaluated.

The arithmetic operators, such as addition (+), subtraction (-), multiplication (*), and division (/)
along with the modulus (%) operator are given equal weightage and are executed from left to
right.

The syntax given below displays an example of the use of parentheses.


trace(3 + 4 * 5); // Displays : 23
trace((3 + 4) * 5); // Displays: 35

Commonly Used Operators


The commonly used operators are as follows:

Arithmetic operators (+, -, *, /): These are the basic operators that you must be familiar
with.

Modulus operator (%): This operator returns the remainder after dividing the first
number with the second. For example,
trace(0 % 3); // Statement 1
trace(5 % 3); // Statement 2
In the above syntax, Statement 1 will display 0 and Statement 2 will display 2.

Increment (++) and decrement ( ) operators: These operators can be used to add or
subtract 1 from a number. As these are unary operators, they require only one argument.
For example,

var x:Number = 5;
x++; // 6
x--; // 5
When the increment or decrement operator is placed before the operand, then 1 is added
immediately before the other variables are processed.

Compound Assignment operators (+=, -=, *=, /=, and %=): These operators can be used to
perform arithmetic on numbers and reassign the answer to the variable on the left. For
example,
x += 1;

In the above syntax, += will add 1 to x and reassign the value to the variable x. Thus, this is
similar to,
x = x + 1;
For detailed step-by-step procedure, refer demo Basic Programming Concepts from:
eResources 4 Me>> My Varsity>> Basic Scripting and Interactivity>> Show Me How

1.4.3 Functions
A function is a piece of code that has been stored and can be called by writing the function name in
the code. Every program written will rely on functions.
It is more important to understand difference between methods and functions. They are commonly
used to describe a reusable block of code. A method is any function defined within a class. Methods
are associated with the instance of the class and tend to act in conjunction with the object in which
they are defined.
For example, a Kitty class might define a function called meow(). Now, meow() would be a method
of the Kitty class. The term method is a distinction in name only. Thus, it does not have any
additional abilities and there is no method keyword.
The syntax to call a function is:
addElementToGroup(myGroup, myElement);
Now, if the same function had to be called on an object instance then the syntax would be:
myGroup.addElement(myElement);
As you can see, the syntaxes are similar, but the latter is designed to act on the myGroup object
instance.
In ActionScript, both terms are used. Function is used for general usage, but when describing
functionality specific to a function defined within a class, the term method is used. Because almost
all functions in ActionScript are stored within classes and most of them are methods.

Calling a Function
A code being executed within a function or method is called calling or invoking. In
ActionScript, a function is called using the functions name followed by a pair of parentheses
(), which is known as the call operator. Within the parentheses, you can pass additional
functions by adding arguments or parameters. Some functions will have optional or required
arguments. The number and type of values passed should match the function definition, also
called a method signature. Other functions require no arguments and are called by using an
empty pair of parentheses.
The syntax of two valid functions are,

trace(Hello!);
addChild(mySprite);

Calling Functions Vs Calling Methods


To access or set a value for a particular property of an object, use the dot syntax followed by
the getter or setter functions. This method is the best way to work with methods as it always
explains the relation of the object and the function. For example,

var nameList:Array = new Array();


nameList.push(James, Smith, John);
nameList.reverse();
trace(nameList); // Displays: John, Smith, James
Some ActionScript statements or operators, such as type of or delete, are technically not
functions even though they appear to behave the same way.

1.5 Controlling Movie Clips


Flash documents contain workspace that consists of text, visual elements, and Timeline. The Timeline
can be used to define the changes done to the elements in the workspace.
Every Flash document contains a Stage, which consists of text, visual elements, and a main Timeline.
This Timeline can be used to define changes to the elements on the Stage. The Stage is the main
movie and may contain multiple movie clips. Each movie clip has its own Timeline and can in turn
include other movie clips.
You can use ActionScript to control movie clips. You can play, stop, move its playhead within its
Timeline, or change its properties, such as size and position. You can use ActionScript to modify
these movie clips to generate content in Flash.
To control movie clips using ActionScript, you need to use the MovieClip class. The methods in this
class have the same functionality as the actions that you use to target movie clips. For most of these
methods, corresponding toolbox options are available in the Actions panel included in Flash.
However, some additional methods do not have the corresponding toolbox options.
If you modify any properties of a MovieClip object, the Flash Player stops the playhead in that
MovieClip object. However, the Flash Player does not stop the playhead in the child MovieClip objects
of that MovieClip object.
Simple tasks that can be performed on a movie clip are:

Make a movie clip play and stop

Work with frame labels in ActionScript

Access scene information in ActionScript

Create instance of library movie clip symbols using ActionScript

Load and control external SWF files, including files created for previous Flash Player versions

Build an ActionScript system for creating graphical assets to be loaded and used at run time.

1.5.1 Using Public Methods


There are various methods available to control the playhead for a movie clip. Some of the methods
are listed as follows:

MovieClip()
To create a new movie clip instance, MovieClip() public method can be used. Once the
movie clip is created, call the addChild() or addChild At() method of a display object
container. The syntax to create a new movie clip is,
public function MovieClip()

gotoAndPlay()
To play a SWF file from a specified frame, gotoAndPlay() public method can be used.
However, the frame will be played only when all the actions in that frame are executed. You
can also specify a particular scene you want to play in the frame by specifying a value for the
scene parameter. The syntax for the same is,
public function gotoAndPlay(frame:Object, scene:String = null):void

gotoAndStop()
In a movie clip, to bring the playhead to a specific frame and to stop it at that frame,
gotoAndStop() public methods can be used. However, this method will be executed only
after execution of all the remaining actions in the frame. In this method, you can also specify a
scene parameter. The syntax to bring the playhead to a specific frame and stop it on that
frame is,
public function gotoAndStop(frame:Object, scene:String = null):void

nextFrame()
To send the playhead to the next frame and stop there, nextFrame() public method can be
used. However, this method will be executed only after execution of all the remaining actions
in the frame. The syntax for the same is,
public function nextFrame():void

nextScene()
To move the playhead to the next scene in the movie clip, nextScene() public method can
be used. However, this method also will be executed only after execution of all the remaining
actions in the frame. The syntax for the same is,
public function nextScene():void

play()
To move the playhead in the Timeline of the movie clip, play() public method can be used.
The syntax for the same is,

public function play():void

stop()
To stop the playhead in the movie clip, stop() public method can be used. The syntax for
the same is,
public function stop():void

prevFrame()
To move the playhead to a previous frame and stop it there, prevFrame() public method
can be used. This method too will be executed only after all the actions in the frame are
executed. The syntax for the same is,
public function prevFrame():void

prevScene()
To move the playhead to a previous scene of the movie clip, prevScene() public method
can be used. This method too will be executed only after all the actions in the frame are
executed. The syntax for the same is,
public function prevScene():void

1.5.2 play() and stop() Methods


A movie clip can be controlled across its Timeline using the play() and stop() methods. For
example, if a movie clip symbol is available on the Stage which contains an animation of a oval object
moving across the screen. Set the instance name of the movie clip to oval. Then, the following code
attached to a keyframe on the main Timeline will not move the animated oval.
oval.stop();
The oval's movement could start through some other user interaction. To play the animation, you
need to create button and apply the following code on a keyframe on the main Timeline.
/*This function will be called when the button is clicked. It causes the oval
animation to play.*/
oval.stop();
function stopAnimation(event:MouseEvent):void {
oval.play();
}
//Register the function as a listener with the button.
startButton.addEventListener(MouseEvent.CLICK, stopAnimation);
Now, create a few buttons with the given instance name and attach the following code to the
keyframe on the main Timeline. You can see that the additional button helps you to increase or
decrease the size of the oval when the animation is played. Event handler has been used for
controlling movie clip. Handling events are better explained in next section.

/*This function will be called when the button is clicked. It causes the oval
animation to play.*/
oval.stop();
function stopAnimation(event:MouseEvent):void {
oval.play();
}
function increaseSize(Event:MouseEvent) {
var sWidth = oval.width;
var sHeight = oval.height;
sWidth++;
sHeight++;
oval.width = sWidth;
oval.height =sHeight ;
}
function decreaseSize(Event:MouseEvent) {
var sWidth = oval.width;
var sHeight = oval.height;
sWidth--;
sHeight--;
oval.width = sWidth;
oval.height =sHeight ;
}
/*Register the function as a listener with the button. Handling events are better
explained in next section.*/
startButton.addEventListener(MouseEvent.CLICK, stopAnimation);
small_btn.addEventListener(MouseEvent.CLICK,decreaseSize);
large_btn.addEventListener(MouseEvent.CLICK,increaseSize);
For detailed step-by-step procedure, refer demo Controlling Movie Clips from:
eResources 4 Me>> My Varsity>> Basic Scripting and Interactivity>> Show Me How

1.6 Basic Event Handling


In ActionScript 3.0, interactivity can be created using the event handling process. Events are
messages that are sent between objects when an action takes place; for example, a button click. In
ActionScript 3.0, you can control the various events using the SWF file. Any such user interaction with
your SWF file is considered an event. Events can also occur without any direct user interaction, such
as when data has finished loading from a server or when an attached camera has become active.

1.6.1 Basics of Handling Events


Any interaction happening within the Flash environment is known as ActioScript Event. Using an
Event Listener, ActionScript can make an object react to any event. An Event Listener is basically a
function created with a specific purpose of reacting to an event. To add an Event Listener
.addEventListener() method can be used. This method registers an event Listener and an event
to an object. For example,
myObject.addEventListener(Event, eventListenerFunction);

The Event Listener is specified by declaring the function the same way like any other function is
declared in ActionScript. The only difference is that the listener function will have one argument to
represent the event. This event argument can have any identifier as its name.
myObject.addEventListener(Event, eventListenerFunction);
function eventListenerFunction (e:Event):void {
//ActionScript statements to be executed when the event happens.
}
In case, a graphical object is to be placed on Stage to act like a button, you can register an event as
an Event Listener as in the code.
myButton.addEventListener(MouseEvent.CLICK, myClickReaction);
function myClickReaction (e:MouseEvent):void {
trace("I was clicked!");
}

1.6.2 Creating Mouse Interactions


Using a simple button, you can create mouse interactions. To create interactions, various mouse
events should be used. Following is the list of useful mouse events.

click: This event occurs when the mouse button is pressed and released over the interactive
display object.

doubleClick: This event occurs when the mouse button is pressed and released twice in a
rapid succession over the interactive display object.

mouseDown: This event occurs when the mouse button is pressed over the interactive
display object.

mouseUp: This event occurs when the mouse button is released over the interactive display
object.

mouseOver: This event occurs when the mouse pointer is moved over the interactive display
object.

mouseMove: This event occurs when the mouse pointer is moved within the interactive
display object.

mouseOut: This event occurs when the mouse pointer is moved outside the interactive
display objects.

mouseWheel: This event occurs when the mouse wheel is rotated while the mouse pointer is
over the interactive display object.

These events can be used by calling addEventListener() on the interactive object and defining
an event handler to handle the MouseEvent passed to it.

1.6.3 Clip Events


Clip events are mostly used along with movie clip objects. In ActionScript 2.0, the syntax to use a clip
event is,
onClip();
In ActionScript 3.0, this has changed and instead of clip event, EventDispatcher has been used. To
use this event handling system, you need to import the following package,
flash.events package
Now, create an oval movie clip, give the instance name as oval, and add the following code to the
keyframe:
function changePosition(event:Event) {
var xPos = oval_mc.x;
var yPos = oval_mc.y;
oval_mc.x = xPos+10;
oval_mc.y = yPos;
}
function changeSize(event:Event) {
var xWidth = oval_mc.width;
var yHeight = oval_mc.height;
oval_mc.width = xWidth+1;
oval_mc.height = yHeight+1;
}
oval_mc.addEventListener(Event.ENTER_FRAME,changePosition);
oval_mc.addEventListener(Event.ENTER_FRAME,changeSize);
You can see that the oval changes its position and size.

Quick Test 1.2


1. In ActionScript, the information stored in variables is known as _____________, till the
program is running.
Objects

Data types

Arrays

Strings

2. To control movie clips using ActionScript, you need to use the _______________
class.
MovieClip

Variable

Method

Function

3. An Action Listener is basically a function created with a specific purpose of reacting to


an event.
True

False

1.7 Data Types


Data types are used to create variables, object instances, and function definitions in the programs.
They describe the kind of value that the variable or ActionScript element contains. There are various
data types available in ActionScript to represent information, such as a single number or a single line

of text. If a particular data type is assigned to a variable, then that variable can hold a value within that
data type's set of values. Some of the simple data types used in ActionScript are String, Numeric, and
Boolean.
While debugging a script, it is necessary to determine the data type of an expression or variable. This
can be done with the instanceof and typeof operators.

1.7.1 Boolean
Boolean values are usually used while working with logical operators. In ActionScript, boolean values
can be used in statements that make comparisons to control the flow of a script. The output of a
boolean value is either true or false. ActionScript converts the true value to 1 and false value to 0.

1.7.2 Number, int, uint


In ActionScript 3.0, three base types of numbers are available.

Number
The Number type is an IEEE 754 double-precision 64-bit floating-point number. It can
represent positive and negative numbers both whole and fractional. Number type can be used
for almost any type of measurement. The default value for an unassigned variable of type
Number is NaN. Usually Numbers are assigned by setting them equal to a numeric literal, but
the Number class also has a constructor, which will attempt to convert the object passed into
a number, and assign it to the new number. For example,

var n:Number;
trace(n); // NaN
n = 12;
trace(n); // 12

int
The int type is a signed 32-bit integer. It is a class and has a constructor like Number that is
rarely used. An int can be created by typing a number literal. If a non-whole number is
assigned to an int variable, then the fractional part of the number will be dropped. The
default value for an unassigned int value is 0. The int type is perfect for counters and is
frequently found in for loops. For example,
for (var i:int = 0; i < 1000; i++)

uint
The uint type is an unsigned 32-bit integer. It is a new data type introduced in ActionScript
3.0 and this too is a class and has a rarely used constructor. unit is similar to int except in
its range of values. Like int, its default value is also 0.

1.7.3 Array
Like numbered list, arrays are a type of ordered set of data. Array type can be used to store any
number of individual pieces of data in a single variable. The Array class also provides methods and

properties. In ActionScript, there are two types of arrays, integer-indexed and associative. Both these
types of array group related data, but use different means of accessing the data.

1.7.4 Object
The Object data type is the base class for all class definitions in ActionScript. It is defined by the
Object class. In ActionScript 3.0, Object data type is not the default data type assigned to variables
with no type annotation.
Occasionally, you may need to store a value in a variable without knowing what type of data it will
hold. For this, ActionScript 3.0 allows you to use wildcard (*) data type. The * denotes that the data
type is unknown until runtime (dynamic) or will accept more than one type of data (example, both
strings and numbers). The wildcard is very useful when creating functions that behave differently
depending on the data type of its parameters.
In ActionScript 3.0, the default value assigned to Object instances is null. Only the untyped variables
can be assigned undefined values. This undefined value is then converted by the Flash Player to the
default value of the particular data type it was assigned to. For example, if you assign an undefined
value to an Object instance, the Flash Player converts it to null, which is the default value of the
Object data type.

Note
ActionScript 3.0 considers the variables with no type annotation as untyped.

1.7.5 String
The fundamental textual element of the ActionScript language is known as strings. Strings are
enclosed in single or double quotes depending upon the number of characters. In ActionScript, single
characters and strings are grouped into String data type and thus are not differentiated.
var exampleA:String = ""; // Empty string
var exampleB:String = "x"; // Single character
var exampleF:String; // Defaults to null when no value is assigned

1.8 Array
The functionality of an array is to store multiple values in a single data structure. The integer-indexed
array stores values using fixed ordinal integer indexes and is simple. The associative array stores
values using arbitrary keys and is complex. You can use any of these types. Arrays can also be multidimensional.
An array provides a way of grouping related data together and then organizing and processing that
data. Arrays can be created in multiple ways.

To create an array with the size defined as 0, the syntax is,


var arrayExample:Array = new Array();

To create an array with the size defined as 10, the syntax is,
var arrayExample:Array = new Array(10);

To create an array with predefined values stored at the declaration Stage itself, the syntax is,
var arrayExample:Array = new Array("Apple","orange","grapes");

In these syntaxes, an array instance named arrayExample is created.

1.8.1 Adding Elements to the Start or End of an Array


An array contains elements and each element has a numeric position. These elements can either
store value or be empty. An element can store a Number, String, or Boolean data type values. It
can also store an array or an object. You can refer to various elements in an array using its position.
You can add elements to an existing array by appending the elements at the end using the
Array.push() method. Pass one or more values to be appended. For example,
var array:Array = new Array();
array.push("val 1", "val 2");
You can also add a single element by using the array's length property as the index as they are zeroindexed, that is, the first index is 0 and not 1. Thus, the last element is at an index of array.length
- 1. For example,
array[array.length] = "val 3";
To add elements to the beginning of an array, use the unshift() method. This shifts the existing
elements by one index position, and inserts the new element at index 0. For example,
// Create an array named animals, "Dog", "Cat", "Rabbit", and "Squirrel".
var animals:Array = new Array();
animals.push("Dog", "Cat", "Rabbit", "Squirrel");
/* Add "Monkey" to the beginning of the array. This shifts all the other elements
so the value "Dog" moves from index 0 to index 1. */
animals.unshift("Monkey");
// Display the results by looping through the elements.
for (var i:int = 0; i < animals.length; i++) {
trace(animals[i]);
}

1.8.2 Searching for Matching Elements in an Array


In ActionScript 3.0, you can search an array for a value using the indexOf() and lastIndexOf()
methods. The following code shows how to create an array and then add elements to it. At last, it
finds the indexes of the elements stored in an array.

var arrayExample:Array = new Array("Apple","orange","grapes");


//Adding an element at the end of an array
arrayExample.push("PineApple");
//Adding elements at the beginning of an array
arrayExample.unshift("Cherry");
arrayExample.unshift("Milk");
arrayExample.push("Apple");
trace(arrayExample);
/*Output will be
Milk,Cherry,Apple,orange,grapes,PineApple,Apple
*/
trace("First index of Apple is "+arrayExample.indexOf("Apple"));
/*Output will be
First index of Apple is 2
*/
trace("Last index of Apple is "+arrayExample.lastIndexOf("Apple"));
/*Output will be
Last index of Apple is 6
*/
To find the first element in an array that matches a specified value, use a for statement to loop
through an array and a break statement to exit the loop once a match has been found.
The break statement used within a for statement causes the loop to exit once it is encountered.
You should place the break statement within an if statement so it is executed only when a certain
condition is met.
Alternatively, you can use any of the following methods:

ArrayUtilities.findMatchIndex()

ArrayUtilities.findLastMatchIndex()

ArrayUtilities.findMatchIndices()

While searching for the first matching element, the importance of the break statement is twofold. It
saves the processing time.
In the following example, the break statement exits the loop after the second iteration. Also, the
break statement is vital when searching for the first match because it ensures that only the first
element is matched and that subsequent matches are ignored. If the break statement is omitted in
the following example, all matching elements are displayed.

//Create an array with eight elements.


var letters:Array = ["a", "b", "c", "d", "a", "b", "c", "d"];
//Specify what we want to search for.
var match:String = "b";
/*Use a for statement to loop through, potentially, all the elements of the
array.*/
for (var i:int = 0; i < letters.length; i++) {
//Check whether the current element matches the search value.
if (letters[i] == match) {
// Do something with the matching element.
// In this example, display a message for testing purposes.
trace("Element with index " + i + " found to match " + match);
//Include a break statement to exit the for loop once a match has been found
break;
}
}

1.8.3 Converting an Array to a String


While working with an array it is good to know the contents within it. You can view the contents using
the trace() method. A comma separated list of values will be displayed.
var names:Array = [Jenny, James, Jack];
trace(names); // Displays: Jenny,James,Jack
An alternative way provided by the Array class can be used to display the values as a string. The
join() method can be used with your choice of string delimiter. For example,
var menu:Array = [Singapore, Hongkong, Japan];
trace(We are going to + menu.join( and ) + . Wow!);
// Displays: We are going to Singapore and Hongkong and Japan. Wow!
The commas are replaced by the word and, making the sentence readable.
To create a string with no spaces or other characters between the array values, use the following
method.
To create a string with no spaces or other characters between the array values use,
empty string: join()

1.8.4 Sorting or Reversing an Array


The sort() method can be used to sort the elements of an array. If no parameters are passed in the
sort() method, then the elements are sorted in ascending order. Elements are sorted according to
the Unicode code points of the characters in the string. This method is useful if you want to sort the
elements of an array alphabetically. For example,

var words:Array = ["Chair", "Pencil", "Table", "Bottle"];


words.sort();
trace(words); // Displays: Bottle,Chair,Pencil,Table
ActionScript allows you to pass one of several constants to the sort() method in order to sort with
different guidelines. Sorting can be done in descending order using the Array.DESCENDING
constant.
var words:Array = ["Chair", "Pencil", "Table", "Bottle"];
words.sort(Array.DESCENDING);
trace(words); // Displays: Table,Pencil,Chair,Bottle
However, sorting in an array is case-sensitive and also it sorts numbers alphabetically and not
numerically. It places elements starting with uppercase characters before elements starting with
lowercase characters.
var words:Array = ["Chair", "pencil", "table", "bottle"];
words.sort( );
trace(words); // Displays: Chair,bottle,pencil,table
For detailed step-by-step procedure, refer demo Array from:
eResources 4 Me>> My Varsity>> Basic Scripting and Interactivity>> Show Me How

1.9 String
A string in Flash can be a piece of textual data from a letter to a word or several paragraphs. Strings
can also contain numbers or non-letter characters. For example, phone number or email id. In
ActionScript 3.0, several methods are available that can be used to manipulate, search, or convert
strings.

1.9.1 Joining Strings


The concat() method can be used to join two or more strings. This method takes multiple
arguments and returns a new string. To join two or more strings, you can also use the string
concatenation operator + or the combination concatenation-assignment operator +=. For example,
var example1:String = "Hello" + "there!";
// This results in a single value of "Hellothere!" (no space)
var example2:String = "Hello" + " " + "there!";
// Results in a single value of "Hello there!" (with a space)
trace(example2);

1.9.2 Using Quotes and Apostrophes in Strings


Quotes or apostrophes can be included within a string. You can use single quotes within double
quotes, or vice versa. While processing the string literals, the ActionScript compiler matches the
quotes of the same kind. Thus, if a string literal is enclosed within quotes of one type and also same
kind of quotes are included in the string value, then the code fails to compile. This string assignment
causes an error because of mismatched quotes.

In the following example, the string starts with a double quote ("Yes); therefore, the double quote
character before the Y signals the end of the string to the compiler. Thus, the compiler does not
understand what to do with the remaining characters,
var error:String = "He said, "Yes.""; // Incorrect.
Thus, the solution is to use single quotes to enclose a string literal that contains double quotes, or
double quotes to enclose a string literal that contains single quotes. For example,
var exampleA:String = 'He said, "Yes."';
// This assignment works. The result is: He said, "Yes."
var exampleB:String = "He said, 'Yes.'";
// This assignment also works. The result is: He said, 'Yes.'

1.9.3 Inserting Special Whitespace Characters


In ActionScript 3.0, you can add whitespace characters, such as tab or new line, with escape
sequence to a string. The escape sequences can be used within a string and are useful while
displaying a string value in a text field. Table 1.1 displays the whitespace characters and its escape
sequence.

Whitespace character

Escape sequence

New line

\n

Tab

\t

Backspace

\b

Form feed

\f

Carriage return

\r

Table 1.1: Whitespace escape sequence


For example,
// Results in a string value: this is an example of tabs
var example:String = " this\tis\tan\texample\tof\ttabs";
/* Results in a string value:
these
words
are
separated
by
newlines
*/
var example:String = "these\nwords\nare\nseparated\nby\nnewlines";

ActionScript 3.0 does not include support for the new line constant. If your code uses new line
anywhere, then replace it with the \\n escape sequence. The result will be the same. For example,
// Generates a compile error replace newline with "\n" to compile
// Compile error: "Access of undefined property 'newline'"
var error:String = "two" + newline + "lines";
Within Flash, the new line, form feed, and carriage return characters all result in the same display.
However, when you load content into Flash from external sources, some values will have new line
characters, some will have form feeds, and some will have carriage returns.

1.9.4 Escaped Characters


Use quotes while using a string literal. This will help the compiler to interpret that the text within the
quotes is a string. For example, to create a piece of text that contains quotes within it, the code will be
as follows:
var s:String = Smith says Thats all folks!;
Now, there will be an error in this code. The output will be Smith says That followed by some junk
characters. This is because the compiler will look for type of quote mark that is used first to end the
string. In such cases, use escaped characters.
Escaped characters are a set of special pseudo-characters that are replaced by the compiler with real
characters. They are always preceded by a backslash. The escape characters for double and single
quotes are \ and \ respectively. Heres an example,
var s:String = Bugs says \What\s up, doc?\;
trace(s); // Bugs says Whats up, doc?

1.9.5 Converting to and from Strings


To display information about any objects in Flash, strings are the preferred method. In ActionScript
3.0, the toString() method should be used to display its value as a string.

Using toString()
The following syntax displays the current date using an instance of the Date class.

var now:Date = new Date();


trace(Todays date is + now.toString());
// Displays: Todays date is Sat Nov 18 22:37:22 GMT-0500 2006
The date is printed in the output as if it is a string. The toString() method is called
automatically in many situations. This is a form of implicit conversion that is built into
ActionScript. If the toString() method was not included as in the following syntax, then the
trace() method will automatically call it on each parameter passed in.
trace(new Date()); // Displays: Sat Nov 18 22:37:22 GMT-0500 2006

Casting to a String (TypeCasting)


The following syntax to set date is wrong, as nowString is a String type of object.
Therefore, a string value is expected.
var now:Date = new Date();
var nowString:String = now; // Causes a compiler error.
In such cases, you need to take care of the object type by converting it into the desired type.
var nowString:String = String(now);

Converting Strings into Other Types


The String class can also be converted into other types. Converting a string containing only
numerical data is as easy as casting it as a Number object. For example,

var shirtSize:String = "12";


var iq:Number = Number(shirtSize);
trace(iq);
However, if you convert it into numbers, the output will result in a nasty NaN (Not a Number)
value.
var dialASong:Number = Number((718) 387-6962);
trace(dialASong); // Displays : NaN
Adding strings and numbers can be confusing, as the compiler will convert the numbers to
strings rather than the other way around.
var a:Number = 2 + 2;
trace(a); // Displays : 22

Converting Strings to an Array


Converting strings to an array is important while processing responses that are received from
the server. The String class contains the split() method that takes two arguments. The
first argument is a delimiter and its type can be a character, string, or regular expression used
to divide up the different elements in the array. The second argument is optional and denotes
the maximum number of elements in the array.

var keywords:String = people,new york,friends,picnic;


var tags:Array = keywords.split(,);
// tags = [people, new york, friends, picnic]
var sentence:String = The quick brown fox jumped over the lazy dog;
var words:Array = sentence.split( , 4); // limit to 4 elements.
// words = [The, quick, brown, fox]
var state:String = Mississippi;
var foo:Array = state.split(ss);
// foo = [Mi, i, ippi]

1.9.6 Getting the Number of Characters in a String


By checking the string objects length property, you can determine the number of characters used in it.
It is similar to arrays length property.
var bigWord:String = PNEUMONOULTRAMICROSCOPICSILICOVOLCANOCONIOSIS;
trace(Number of letters: , bigWord.length); // Displays: 45
The length is a read-only property. Its value changes only when characters are added or deleted
from the string object.

1.9.7 Getting a Particular Character


You can access an individual character from a string object using the charAt() method. This
method returns the character located at a specified index. For example,
var firstName:String = Neal;
trace(name.charAt(1)); // Displays: e

1.9.8 Converting Case


The toUpperCase() and toLowerCase() methods can be used to change the case of a string or
perform a case-insensitive comparison. Both these methods return a new string in which all the
characters are in uppercase or lowercase depending upon the method used. The original string is not
modified. This is useful in situations when you want to ensure uniformity of case. For example, to
perform case-insensitive searches within strings, you can use these methods.
var example:String = "What case?";
trace(example.toLowerCase());
// Displays: what case?
trace(example.toUpperCase());
// Displays: WHAT CASE?
trace(example);
// The original string value is unchanged: What case?
As both these methods return a new string, you can alter the original string by reassigning the return
value to it. For example,
var examples:String = "What case?";
examples = examples.toLowerCase();
For detailed step-by-step procedure, refer demo String from:
eResources 4 Me>> My Varsity>> Basic Scripting and Interactivity>> Show Me How

Quick Test 1.3


1. ____________________ are usually used while working with logical operators.
Arrays

Objects

Boolean values

Strings

2. The ______________ array stores values using arbitrary keys.


Integer-indexed

Abstract

Matrix

Associative

3. Strings can also contain numbers or non-letter characters.


True

False

1.10 Summary
In this session, Introduction to ActionScript 3.0 and Programming Concept, you learned that:

ActionScript can be added to your application by using the Actions panel, Script window, or
any other external editor.

A computer program is a series of instructions and steps that are executed using a computer.

The Actions panel allows you to create and edit ActionScript code for an object or a frame.

The Script pane is used to enter the code.

Movie Explorer is a panel that displays all the items of the movie, as well as the movie
structure.

The trace() statement is used to send specific information to the Output panel.

Using comments you can temporarily deactivate a part of the code.

Variables can be a representation of numbers, string of characters, or some other values.

In ActionScript, a variable can be declared or created using the var statement.

Operators are built-in function like commands that operate on one or more values.

A function is a piece of code that has been stored and can be called by writing the function
name in the code.

A code being executed within a function or method is called calling or invoking.

Every Flash document contains a Stage, which consists of text, visual elements, and a main
Timeline.

A movie clip can be controlled across its Timeline using the play() and stop() methods.

Any interaction happening within the Flash environment is known as ActioScript Event.

Data types are used to create variables, object instances, and function definitions in the
programs.

Array type can be used to store any number of individual pieces of data in a single variable.

In ActionScript 3.0, you can search an array for an value using the indexOf() and
lastIndexOf() methods.

The sort() method can be used to sort the elements of an array.

A string in Flash can be a piece of textual data from a letter to a word or several paragraphs.

In ActionScript 3.0, you can add whitespace characters, such as tab or new line, with escape
sequence to a string.

1.11 Exercise
1. Using the__________________, you can swap quickly between the scripts in a Flash
document.
Actions Toolbox
Script Navigator
Script Pane
Movie Explorer
2. ______________ are built-in function-like commands that operate on one or more values.
Operators
Variables
Arrays
Functions
3. Each movie clip has its own Timeline and can in turn include other movie clips.
True
False
4. The _____________ method can be used to move the playhead to the next scene in the
movie clip.
nextFrame()
gotoAndStop()
gotoAndPlay()
nextScene()
5. The prevScene() public method can be used to move the playhead to a previous scene of the
movieclip.
True
False
6. The ________________ event occurs when the mouse pointer is moved within the interactive
display object.
mouseOver
mouseOut
mouseMove
mouseWheel

7. The output of a boolean value is either true or false.


True
False
8. The _____________ method can be used to sort the elements of an array.
indexOf()
sort()
trace()
lastIndexOf()

Se ssi on 2

Working with Built-in Classes


Learning Outcomes
In this session, you will learn to:

Make logical decisions using conditional statements


Use loops
Create a blank movie clip
Load an external SWF file
Use hitTest() method to detect collision in an SWF file
Retrieve data from the text field
Use autoSize property
Display HTML text in a text field
Work with advanced text layout
Create a password field
Format text
Use date and time
Create and open a local shared object
Add and save data in a local shared object
Read values from a local shared object
Load an external file

In the previous session, you learned about the programming fundamentals and the basic
programming concept. You also became familiar with the different data types. In this session, you will
learn about the various built-in classes and become familiar with the conditional and loop statements.
You will also be able to work with movie clips and text fields. You will learn to make use of date and
time as per your requirements and also be able to load external files.

2.1 Conditions and Loops


2.1.1 Conditions
While making logical decisions for a given situation, conditional statements can be used. Conditional
statements can be used to perform an action when a particular condition is true.
You can use conditions like if statement or switch statement. The if statement evaluates the truth
of a logical expression and allows you to program different outcomes for different results. The switch
statement can be used when several possible conditions are to be tested. Flashs ternary conditional
operators can be used to perform conditional checks on a single line of code.

if Statement
This is the commonly used statement. An if statement allows you to execute a piece of code
only if a certain condition is met.

var correctAnswer = 20;


if (userEntery == correctAnswer) {

trace("that is correct");
}

Note
The brackets {} are optional for statements with only one line. But, for consistency, always
make use of the brackets.

else Statement
If the if condition is false, then the else clause can be used in order to perform alternative
actions. But for the trace() command to have any effect, the SWF file must be compiled
using the Debug, and not Run mode. Call the method named showMessage(). It displays an
appropriate message depending on whether the user got the answer right or wrong.

Note
In place of double quotation mark, single quotation marks can be used.

var userEntery = 30;


var correctAnswer = 20;
if (userEntery == correctAnswer) {
trace("that is correct");
}
else {
trace("That's incorrect");
}

Switch Case
To test a single expression against several possible conditions, you can use the switch
statement. This statement uses more than one if-else clauses. Instead of testing a
condition for a Boolean value, the switch statement evaluates an expression and uses the
result to determine which block of code to execute. Blocks of code begin with a case
statement and end with a break statement. The break statement tells the conditional
statement or loop to cancel the rest of its operation without going any further.

var sColor:String = "RED"; // value accepted should be on of the default


colors.
switch (sColor) {
case "RED":
trace("the color added is red");
break;
case "BLUE":
trace("the color added is blue");
break;

case "Green":
trace("the color added is green");
break;
default:
trace("there is no color added");
break;
}
For detailed step-by-step procedure, refer demo Using Conditional Statements from:
eResources 4 Me>> My Varsity>> Basic Scripting and Interactivity>> Show Me How

2.1.2 Loops
Loops can be used when you need to count through a set of data. This control structure performs the
same task multiple times within a single frame. For example,
for (var i:int = 0; i < 10; i++) {
// Display the value of i
trace(i);
}
With the help of the loops, you can perform operations that are difficult to perform manually. The
various loops available are:

for Loop
This is the most common looping structure. Example,

for (var i:int = 1; i <= 100; i++) {


// Do some action
}
In the above syntax, an integer i is declared and set to 1. This will be the number that counts
up during each loop. The next part of the syntax shows the conditions for the loop to continue
running. This is like the if statement. It evaluates the condition that says if i is less than or
equal to 100, then keep looping or else stop. The next portion of the syntax is called the
iterator. It tells the for loop what to do at the end of each loop. An increment operator (++) is
used to add one to the counter variable. It is equivalent to i = i + 1.

while Loop
This is a basic type of looping. This can be used when you want to meet a particular condition.
For example,

while (condition == true) {


// do some action
}

In the above syntax, the action will continue till the condition is true. The while statement can
be used to loop a variable until it reaches a certain value. For example,
var sum:Number = 0;
while (sum < 100) {
trace(sum + " - not there
var randomNumber:Number =
// create a random number
sum += randomNumber;
}
trace(sum + "- surpassed 100.

yet.");
Math.ceil(Math.random() * 10);
between 0 and 10

END");

In the above syntax, the loop adds random numbers together until the result surpasses 100.

do while Loop
In this type of looping, the condition is checked after the loop is complete instead of checking
before. So at least one iteration takes place. For example,

var sum:Number = 10;


do {
sum += 40;
} while (sum < 10);
trace(sum + " - surpassed 10"); // Displays: 50 - surpassed 10
For detailed step-by-step procedure, refer demo Creating Loops from:
eResources 4 Me>> My Varsity>> Basic Scripting and Interactivity>> Show Me How

2.2 Working with Movie Clips


2.2.1 Creating Blank Movie Clip with Script
In ActionScript 3.0, movie clip and instance created programmatically will not be visible on the screen
till they are added to the display list. A movie clip can be added to the list by calling the addChild()
or addChildAt() method. These methods allow you to create a movie clip, set its properties, and
even call methods before the clip is rendered to the screen.

2.2.2 Attaching Movie Clip from Library


By default, instances of movie clip symbols in a Flash document's library cannot be created
dynamically. This is because each symbol that is exported for use in ActionScript adds to the size of
your SWF file. It is then recognized that some symbols might not be intended for use on the Stage.
For this reason, in order to make a symbol available in ActionScript, you must specify that the symbol
should be exported for ActionScript.

2.2.3 Loading an External SWF File


To load an external SWF file, the new Loader class can be used. An SWF file can be accessed via
the content property of the Loader instance. If the Loader is in the main display hierarchy, the .swf
also appears on screen.
ActionScript 3.0 needs to do the following in order to load an external SWF file:

Create a new URLRequest object with the URL of the file.

Create a new Loader object.

Call the Loader objects load() method by passing the URLRequest instance as a
parameter.

Call the addChild() method on a display object container to add the Loader instance to
the display list.

For example, a dummy.swf file uses the same technique of calling the load() method on a Loader
instance and passing a URL to a .swf instead of an image, the .swf is loaded into the movie.
var request:URLRequest = new URLRequest("dummy.swf");
var loader:Loader = new Loader()
loader.load(request);
addChild(loader);
You can access an SWF file once it is successfully loaded. It can be accessed through the
Loader.content property. If the external SWF file is published for ActionScript 3.0, it will be either a
movie clip or a sprite, depending on which class it extends.

2.2.4 Testing Collision of Movie Clips


In an SWF file, the hitTest() method of the MovieClip class detects collision. It checks to see if
an object has collided with a movie clip and returns a Boolean value. Using the hitTest() method,
you can check whether a collision has occurred or determine whether one movie clip has reached
another. The parameters of the hitTest() method can be used to specify the x and y coordinates of
a hit area on the Stage or use the target path of another movie clip as a hit area.
After specifying the x and y coordinates, the hitTest() method returns true if the point identified by
(x, y) is a non-transparent point. When a target is passed to hitTest(), the bounding boxes of the
two movie clips are compared. The hitTest() method returns a true value if they intersect or else it
returns a false value.
Now, for example, create two movie clips on the Stage and give them the instance names as
car1_mc and car2_mc. Then, perform test collision detection between these clips. On the first
Frame of the Timeline, enter the below given code.
import flash.text.TextField;
// functionality
var myMc:MovieClip = new MovieClip();
var startPoint:Number =car1_mc.x;
var endPoint:Number = car2_mc.x;
// Variable for testing the collision is been created
var sResult:Boolean;

// Listen has been added to monitor the enter movement


myMc.addEventListener(Event.ENTER_FRAME, detectionMotion);
/*Function accepts a movie clip name, does an name testing and accordingly
increases or decreases the movie clip size and decides the x position variables.
This is then added to the MovieClip() object on the Stage. A text field is created
which reflects the collision detection message once the collision is done. The
removeListener is used to unregister the enterframe function.*/
function fnMove(sMovieClip:MovieClip) {
if(sMovieClip.name == "car1_mc") {
car1_mc.x =startPoint;
startPoint++;
} else if(sMovieClip.name == "car2_mc") {
car2_mc.x = endPoint;
endPoint--;
}
sResult =car1_mc.hitTestObject(car2_mc);
if(sResult) {
trace("Movies have collided");
myMc.removeEventListener(Event.ENTER_FRAME, detectionMotion);
var field:TextField = new TextField();
field.x = car1_mc.x-10;
field.y = car1_mc.y+35;
field.text = "Cars have collided";
addChild(field);
}
}
// call is made to the fnMove function in the below code.
function detectionMotion(event) {
fnMove(car1_mc);
fnMove(car2_mc);
}
According to the above code, whenever the bounding box of car1_mc intersects the bounding box of
car2_mc, the status displays Movies have collided.
For detailed step-by-step procedure, refer demo Testing Collision of Movie Clips from:
eResources 4 Me>> My Varsity>> Basic Scripting and Interactivity>> Show Me How

2.2.5 Duplicating or Removing a Movie Clip


In ActionScript 3.0, the addChild() method can be used to duplicate the movie. This method only
duplicates the selected movie clip, thus the rest of the application remains the same. The duplicated
movie clip always starts from Frame 1, irrespective of the position of the original movie clip in another
frame. The duplicate movie clip is always placed in front of all the previously defined movie clips
placed on the Timeline. In the earlier versions of ActionScript, the duplicateMovieClip() method
was used.

To delete a movie clip, the removeChild() method can be used. If a duplicate movie clip is deleted,
then the parent movie clip is deleted.

2.3 Working with Text Fields


In any Web application, text is an essential aspect and text field is the base object for dealing with text
anywhere in Flash Player 9.0. It handles text fields, where a user can enter text as in a form. Similarly,
text can also be displayed by setting its type to either input or dynamic.
The flash.text.TextField class is the way in which all text is displayed in Flash Player. The
text components, such as TextArea and TextInput, use the TextField class to display text.
Flash Player gives you multiple ways to communicate with text fields by enabling user input,
embedding fonts, and using Cascading Style Sheets.

2.3.1 Accessing the Text from a Text Field


Accessing data or retrieving data from a text field is mostly used in places where interactivity or user
inputs are required. This type of functionality is often seen when data from the user has to be
accepted and processed to either display it on screen or forward to some backend database for
storing purpose. To access data, following syntax can be used.
var displayString:String;
displayString = TextFieldName.text;
The data received from the text field should be stored in the variable as it is required for further
manipulation. The stored data can also be typecasted at the time of accessing.
The example given below is of accessing data from the input text field. You can create an input text
field and a Submit button with its instance names as input_txt and submit_btn. Create an additional
layer and attach the code on the first Frame of the Timeline.
function AccessingData(Event:MouseEvent) {
var sTemp = input_txt.text;
trace(sTemp +" hello there");
}
submit_btn.addEventListener(MouseEvent.CLICK,AccessingData);
If you insert James in the input field and click the Submit button, the output window will display,
James hello there.

2.3.2 Controlling the Text of a Text Field with a Script


The autoSize property can be used to size a text field's viewable area to fit the text. The text
automatically resizes itself in order to fit in the text field. By default, the autoSize property is set to
NONE, that is, the text will not automatically resize by itself.
The autoSize property should be set to LEFT if you want the text field to resize while fixing the
upper-left corner's position. In other words, the text field's lower-right corner is the point that moves
when it expands and contracts. You can use the below given syntax to set the property of the text to
left.

// These two lines do the same thing


field.autoSize = TextFieldAutoSize.LEFT;
field.autoSize = true;
The autoSize property should be set to CENTER if you want the text field to be anchored at its
center point. While the top of the object remains fixed, it expands and contracts downward and
equally to the right and left. The syntax for the same is,
field.autoSize = TextFieldAutoSize.CENTER;
The autoSize property should be set to RIGHT if you want the upper-right corner of the text field to
remain steady while the object expands and contracts in the direction of the lower-left corner. The
syntax for the same is,
field.autoSize = TextFieldAutoSize.RIGHT;

2.3.3 Display of HTML Text


A limited subset of HTML is supported by Flash that can be displayed in the text field. The text fields
interpret and display the basic HTML tags if they are properly configured. By using HTML in a text
field, you can add hyperlinks and also do basic formatting in your content. The value of the text field
object's htmlText property is interpreted as HTML.
field.htmlText = "<u>This displays as underlined text.</u>";
The text property of a text field is rendered as plain text. This means that even if the text property is
set to <u>test</u>, the object displays <u>test</u> instead of test. It means if you want to
display HTML code in its unrendered format, assign the HTML value to the text property of the text
field, as shown below:
field.text = "<u>underlined text</u>";
/* text field displays:
<u>underlined text</u>
*/
This can be a useful technique if, for example, you want to show both the rendered HTML and the
HTML source code in side-by-side text fields,
htmlCode = "<i>italicized text</i>";
sourceHTML.text = htmlCode;
renderedHTML.htmlText = htmlCode;

2.3.4 Selecting and Manipulating Text


You can highlight a portion of the text within a text field using the TextField.setSelection()
method. This method takes two parameters:

startIndex: The beginning, zero-relative index of the text to highlight.

endIndex: The index of the character after the text to highlight.

The selection works only if the text field has focus. The syntax to set focus is:

stage.focus = field; // Sets the focus to the text field


field.text = "this is example text"; // Sets the text value
field.setSelection(0, 4); // Highlights the word "this"
The selectionBeginIndex and selectionEndIndex properties can be used to retrieve the
indices of the selected character range.

Working with Advanced Text Layout


While working with advanced text layout, you can use the numLines property and the
getCharBoundaries(), getCharIndexAtPoint(), getFirstCharInParagraph(),
getLineIndexAtPoint(), getLineIndexOfChar(), getLineLength(),
getLineMetrics(), getLineOffset(), getLineText(), and
getParagraphLength() methods.
In the earlier versions of Flash, it was difficult to control and read text layout with much
precision. Now, the TextField class defines an API for more precise reading of text layout.

Replacing Text
To replace the selected text in a text field, use the replaceSelectedText() method. To
replace a range of text, the replaceText() method can be used. This method replaces the
text within a text string. You need to mention the start and end index of text. Syntax for both
these methods are as follows:
field.ReplaceSelectedText("new text");
field.replaceText(100, 150, "new text");
The replaceText() method replaces text from index 100 to index 150, with the new string
specified by the third parameter.

2.3.5 Restricting User Input


The inputs received from the user can be controlled by using a password input field and by filtering
text input.

Making a Password Field


When a password is entered in the password field, the text gets converted to asterisks by
default. This is because the TextField.password property is set to True.
When the password property is set to True, all text entered into the text field, either
programmatically or by user, is displayed as asterisks. The syntax for the same is,
field.password = true;
field.text = "example text"; // Text field displays: ************
Copying from the password text field is restricted. Thus, the user cannot copy password and
paste it into a plain text document.

Filtering Text Input


In the input field, you can enter any characters. However, in some cases, you need to restrict
some characters. For example, in case of an input field for telephone numbers, the characters
should be restricted to numbers and dashes.
The TextField.restrict property lets you specify the characters that are allowed for user
input into a field. Specify a string containing the allowable characters, such as,
field.restrict = "a-j";

This syntax allows the user to enter any of the allowable characters, that is, a, b, c, d, e, f, g, h, I
and j. Other characters are restricted. If the user tries to enter grabs, only gab appears, since the
letters r and s are not in the allowable character set.

2.3.6 Formatting Text with Text Format


Formatting of text in the text field can be done in the following ways:

Using the HTML tags, such as <font>, <b>, and <u>

Passing a TextFormat object to the TextField.setTextFormat() method

Using a StyleSheet object and applying it to the text field's styleSheet property

However, the color of the entire content can be set using the textColor property.
Applying HTML formatting is relatively simple, but it is often difficult to manage different techniques.
Using TextFormat object is complex than formatting via HTML. However, when formatting via
HTML, often it is difficult to manage different techniques. Using CSS with a StyleSheet object
allows you to load a CSS document, which makes it simple to maintain. Thus, you can edit the CSS
document without having to re-export the SWF file.
For quick and simple formatting, HTML tags can be used. For example, the following code displays
bold and underlined text.
field.HTML = true;
field.htmlText = "<b>Bold text</b> <u>Underlined text</u>";

2.3.7 Formatting User-Input Text


You can also apply formatting to text as the user enters it into a text field. This can be done by
applying a TextFormat object using the defaultTextFormat property of the text field. The syntax
for the same is,
var formatter:TextFormat = new TextFormat();
formatter.color = 0x0000FF; // Make the text blue
field.defaultTextFormat = formatter;

Quick Test 2.1


1. The ___________ statement evaluates the truth of a logical expression and
allows you to program different outcomes for different results.
endif

if

elseif

ifthenelse

2. Loops perform the same task multiple times within a single frame.
True

False

2.4 Use of Date and Time


In ActionScript applications, dates and times are important. Time and dates are used in order to keep
a record of total time elapsed for the timed operations and to store transaction dates. They are also
used to determine whether a users trial membership is active or about to expire.
The Date class can be used to set and get date and time values in terms of years, months, days, and
so on by using properties such as fullYear, month, and so on.

2.4.1 Finding the Current Date and Time


Using the Date() constructor, you can create a new date to display the current date and time.
Alternatively, use a CGI script or any other server side program to return the server time and create a
new Date object from that value.
The ActionScript calculates the date and time based on the client side computer. If the users
computer displays incorrect time, the Date object will display the same.
Therefore, you need to create a new Date object by using a constructor without parameters in order
to retrieve the current client-side date and time.
// Create a new Date object.
var current:Date = new Date();
// Displays client-side date and time.
trace(current);

2.4.2 Retrieving the Date Values


The Date object can be used in order to retrieve the year, month, day of the month, day of the week,
hour, minute, second, or millisecond value. The various properties supported by the Date object are:

fullYear: Specifies the year as a four-digit value, such as 2010.

date: Specifies the day of the month as a value from 1 to 31.

month: Specifies the month as an integer from 0 (January) to 11 (December).

day: Specifies the day of the week as an integer from 0 (Sunday) to 6 (Saturday).

hours: Returns the hours value as an integer from 0 (midnight) to 23 (11 p.m.).

minutes and seconds: Return values from 0 to 59.

milliseconds: Returns a value from 0 to 999.

Each of these properties have a Coordinated Universal Time (UTC), also known as Greenwich Mean
Time (GMT) correspondent. For example, although the hours property returns the current hours value
based on the client computer's clock, the hoursUTC property returns the current hours value in UTC
time.

2.4.3 Retrieving the Day or Month Name


Arrays can be created to retrieve the name of the day or month. These arrays should contain string
values for the names of the days of the week and the names of the months of the year. You can make
use of numeric day and month to extract the string values from the arrays.
In ActionScript, the Date class provides the day and month properties, which return integer values
representing the day of the week (from 0 to 6) and the month of the year (from 0 to 11). However, you
may want the name of the day or month instead of its zero-relative number.
To address this, create array. For example,
public static const DAYS:Array
var DAYS:Array = new Array();
var DAYSABBREVIATED:Array = new Array();
var MONTHS:Array = new Array();
var MONTHSABBREVIATED:Array = new Array();
DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday"];
DAYSABBREVIATED = ["Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"];
MONTHS = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
MONTHSABBREVIATED = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"];
For detailed step-by-step procedure, refer demo Use of Date and Time from:
eResources 4 Me>> My Varsity>> Basic Scripting and Interactivity>> Show Me How

2.5 Video Compositing


Shared objects can be used to personalize programs, retain preferences, and improve experience. By
creating these shared objects, you can store all kinds of information that can be retrieved when the
program is executed again. You can retrieve the same information on restarting the program. The
data will not be lost even after the user shuts down the browser or computer.
Information about the systems hard drive cannot be accessed or modified using ActionScript. Thus,
you can use local shared objects to save program related data.

2.5.1 Creating and Opening a Local Shared Object


Local shared object work in a similar manner as cookies. Using local shared object, you can store and
retrieve many basic ActionScript data types. The default maximum size of local shared object is 100
KB. Files are saved to the client computer in a binary format with .sol extension. Flash movies within

the same domain can write to and read from the .sol files by means of ActionScript's
flash.net.SharedObject class.
All the .sol files created are stored in an application data directory for the Flash Player. It is the
standard location for the storage.
The local shared objects are created and opened for reading using the static getLocal() method.
This method requires one parameter, that is, a string that specifies the name of the shared object. For
example,
var example:SharedObject = SharedObject.getLocal("example");
The getLocal() method first tries to locate an existing local shared object by the specified name
with a .sol extension stored on the client computer. If none is found, the Flash Player creates a new
local shared object with that name. In either case, the existing or new local shared object is opened.

2.5.2 Writing Data to a Shared Object


To add data to a local shared object, you need to add the values as properties of the shared object's
data object. The shared objects have a special built-in property named data. The data property is an
object to which you should add any information that you want to store in the shared object. For
example,
// Store a username value to the example shared object.
example.data.username = "Darron";
The properties can no longer be attached directly to the shared object. A compile-time error will be
generated if the data is stored in the SharedObject instance instead of the data property. This
prevents potential erroneous attempts to save data.
example.variable = "This will cause a compile-time error.";
Additionally, trying to assign a value to the data property directly is incorrect.
example.data = "This will cause another compile-time error.";
The correct approach is to attach the value to a new property under data property, as follows:
example.data.variable = "This is the correct way to store data.";

2.5.3 Saving a Local Shared Object


The SharedObject.flush() method can be used to save data in a local shared object to the client
computer. Flash automatically saves the local shared object to the disk when the movie is unloaded
from the player. The local shared object is also saved when the SharedObject instance is collected
or when the SharedObject.clear() method is invoked.
var flushResult:String = example.flush();
An optional parameter can be passed in the flush() method that specifies the minimum amount of
disk space, in bytes, that can be used while writing the shared object.
The default value is 0, which means only the minimum required space should be used to write the
local shared object to disk.

2.5.4 Reading Data from a Shared Object


To read values that have been stored in a local shared object, you should use the properties stored in
the shared objects data property.
It is easy to read values from a client-side shared object. All the values are stored in the shared
objects data property. The code given below is an example of a phone book. Two buttons should be
created with the instance names add_btn and display_btn. Similarly, an input text field and a
dynamic text field should also be created with the instance names phone_txt and display_txt. Next,
on the first frame of the Timeline, enter the following code.
var myPhoneBook:SharedObject = SharedObject.getLocal("myPhoneBook");
//Checking if the phone book is present, if not it will create new
if (myPhoneBook.data.created == undefined) {
myPhoneBook.data.PhoneNumber = new Array();
myPhoneBook.data.created = 1;
}
//Array created to update multiple values
var PhoneArray:Array = new Array();
//listener had been added to add and display button.
add_btn.addEventListener(MouseEvent.CLICK, addToList);
display_btn.addEventListener(MouseEvent.CLICK, displayNumbers);
/*function add the phone number to display list once the user has enter values in
textfield and clicked on submit button.*/
function addToList(Event:MouseEvent) {
var sPhoneNumber= phone_txt.text+"\n";
PhoneArray.push(phone_txt.text);
myPhoneBook.data.PhoneNumber.push(phone_txt.text);
myPhoneBook.flush();
display_txt.appendText(sPhoneNumber);
}
/*display function is used to retrieve all the existing phone numbers which have
been stored on the local drive.*/
function displayNumbers(Event:MouseEvent) {
PhoneArray = myPhoneBook.data.PhoneNumber;
for(var i =0; i<PhoneArray.length; i++) {
var sTemp = PhoneArray[i]+"\n";
display_txt.appendText(sTemp);
}
}

2.6 Loading External Files


The flash.display.Loader class can be used to load an external bitmap image. By accessing
the bitmapData property of the bitmap, you can directly access the bitmap image. This takes the
URLRequest object with the URL of the image you are loading. Listening for the loader's complete

event lets you know when the image is loaded. The below shown is an example to create the
loaderlisten for the complete event and begin loading an image.
import flash.display.Sprite;
import flash.display.Loader;
import flash.events.Event;
// For image loading.......
var sLoader:Loader = new Loader();
sLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadingComplete);
sLoader.load(new URLRequest("Sunset.jpg"));
function onLoadingComplete(event:Event):void {
var myImage:Bitmap = Bitmap(sLoader.content);
addChild(myImage);
}
Before publishing the file to see the result, ensure that an image is placed in the root folder. You can
now see that bitmap is loaded in the SWF file.
Similarly, you can load the text file by using the below given script.
import flash.display.*;
import flash.text.*;
import flash.events.*;
import flash.net.*;
var dataLoader:URLLoader = new URLLoader();
var display_txt:TextField = new TextField();
display_txt.width = stage.stageWidth;
display_txt.height = stage.stageHeight;
addChild(display_txt);
dataLoader.addEventListener(Event.COMPLETE, displayData);
dataLoader.load(new URLRequest("author.html"));
function displayData(event:Event) {
display_txt.htmlText = dataLoader.data;
}
For detailed step-by-step procedure, refer demo Loading External Files from:
eResources 4 Me>> My Varsity>> Basic Scripting and Interactivity>> Show Me How

Quick Test 2.2


1. Using the ____________ constructor, you can create a new date to display the
current date and time.
Dateandtime()

date()

day()

systemdatetime()

2. It is difficult to read values from a client-side shared object.


True

False

3. The _____________________ class can be used to load an external bitmap


image.
insert()

modifyimage()

Callbitmap()

flash.display.loader

2.7 Summary
In this session, Working with Built-in Classes, you learned that:

Conditional statements can be used while making logical decisions for a given situation.

An if statement allows you to execute a piece of code only if a certain condition is met.

If the if condition is false, then the else clause can be used in order to perform alternative
actions.

The switch statement can be used to test a single expression against several possible
conditions.

Loops can be used when you need to count through a set of data.

The while statement can be used to loop a variable until it reaches a certain value.

In do while loop, the condition is checked after the loop is complete instead of checking
before.

To load an external SWF file, the new Loader class can be used.

In ActionScript 3.0, the addChild() method can be used to duplicate the movie.

To delete a movie clip, the removeChild() method can be used.

The flash.text.TextField class is the way in which all text is displayed in Flash Player.

A limited subset of HTML is supported by Flash that can be displayed in the text field.

To replace the selected text in a text field, use the replaceSelectedText() method.

The Date object can be used in order to retrieve the year, month, day of the month, day of
the week, hour, minute, second, or millisecond value.

Shared objects can be used to personalize programs, retain preferences, and improve
experience.

The SharedObject.flush() method can be used to save data in a local shared object to
the client computer.

The flash.display.Loader class can be used to load an external bitmap image.

2.8 Exercise
1. To display an appropriate message depending on whether the user got the answer right or
wrong, you should call the ______________ method.
trace()
showMessage()
displayMessage()
load()
2. To delete a movie clip, ________________ method can be used.
removeChild()
eraseChild()
deleteChild()
duplicateMovieClip()
3. The text components, such as TextArea and TextInput, use the TextField class to display text.
True
False
4. By default, the autoSize property is set to ______________.
CENTER
RIGHT
LEFT
NONE
5. The BeginIndex and EndIndex properties can be used to retrieve the indices of the selected
character range.
True
False
6. The ____________ property specifies the year as a four-digit value, such as 2010.
date
month
fullYear
year
7. The ____________________ method can be used to save data in a local shared object to the
client computer.
SharedObject.flush()
SharedObject.clear()
flash.display()
getLocal()

Se ssi on 3

Object-Oriented Programming with


ActionScript 3.0
Learning Outcomes
In this session, you will learn to:

List some of the object-oriented programming tasks

Define a class

Define a package

Write a class

Create properties, methods, and object instances

Set classpath

Inherit from an existing class

Describe encapsulation

Describe polymorphism

Describe the three types of elements available in display list

In the previous session, you learned about the conditions and loop statements. You also learned to
work with movie clips, and text fields. In this session, you will learn about object-oriented concept,
classes, and packages. You will learn to create static methods and properties. You will also become
familiar with terms, such as polymorphism and
encapsulation. In Flash, the MovieClip class
happens to be one of the key classes. You will learn to extend this class.

3.1 Object-Oriented Concept


Object-oriented programming is a technique for programming a paradigm for writing programs for a
set of problems. Basically, it is a way of organizing the code in a program by grouping it into objects
individual elements that include information and functionality. It includes strategies and techniques for
designing a program. Using an object-oriented approach to organize a program, you can group
particular pieces of information having common functionality.
The common object-oriented programming tasks are:

Defining classes

Creating properties, methods, and get and set accessors (accessor methods)

Controlling access to classes, properties, methods, and accessors

Creating static properties and methods

Creating enumeration-like structures

Defining and using interfaces

Working with inheritance, including overriding class elements

3.2 Classes and Packages


In object-oriented programming, classes are versatile and play multiple roles. In ActionScript 3.0, it is
essential to use classes while programming. Objects are high-level building blocks, and classes are
the constructs which define them.
The ActionScript class files are organized in packages while creating classes. A package is a
directory that contains one or more class files and that resides in a designated class path directory. A
package can, in turn, contain other packages, called subpackages, each with its own class files.
A class is a blueprint for an object. It defines the object in full, that is, the data and its operations.
Program uses classes to create new objects and to manipulate types. Classes contain the code you
write. When a program is executed, the organized production of objects is directed by the code in the
classes.
A package is a way of organizing classes into groups. Large projects can contain multiple classes.
The functionality of Flash Player is exposed in dozens of classes, which are also grouped by function.
Packages are structures that group classes together, define the full name for the classes they contain,
and add a level of access control. Packages can be nested arbitrarily using dot notation.
Classes can be referred by their class name, for example, Rectangle. The full name is not required
as the Rectangle class is present in the flash.geom package. The class has a fully qualified
name, that is, flash.geom.Rectangle. Similarly, if you have established a class named Jack,
which means Jack Smith, then at any instance you can refer Jack, as there is only one Jack class
in the whole scene. Similarly, the same principle can be applied while writing different programs.

3.3 Writing Class


While starting to write a new custom class, save a new file with the .as file extension and the
filename similar to the name of the class. Then, add the class definition to the file.
package packageName {
public class ClassName {
}
}
In all the applications of ActionScript 3.0, class is the base. Classes must be saved in a plain text file
with an .as extension. There can be one public class definition in a single .as file and the name of
the file must be same as the name of the class. For example, if you name a class as Circle, then the
file name will be Circle.as.
In a class, you should declare a package first. The syntax for declaring a package is,
package name {
}
In case, if the class file is saved in a subdirectory of example called subpackage, the package
declaration is as follows,
package example.subpackage {
}

While working with classes, packages are an important part as they allow you to ensure that your
classes do not conflict with any other classes.
For detailed step-by-step procedure, refer demo Classes and Packages from:
eResources 4 Me>> My Varsity>> Basic Scripting and Interactivity>> Show Me How

3.4 Using Attributes to Class and its Methods and


Properties
3.4.1 Creating Properties that Behave as Methods
In a program, if you use public properties that behave like methods, then you must not break
encapsulation. All properties should be declared as private or protected.
public properties are appropriate because of a principal called encapsulation. Using public
properties, you can easily break a class or an instance of a class.
package {
public class Counter {
public var count:uint;
public function Counter() {
count = 0;
}
}
}
In the above code, you can create an instance of Counter class and can also change the count
property value. For example,
var counter:Counter = new Counter();
counter.count++;

3.4.2 Creating Static Methods and Properties


Properties and methods are instances defined for a class. If the Counter class defines a count
property and a getCount() method, then, by default, each instance of Counter has its own count
property and getCount() method. However, there are cases in which you want the property or
method to be associated with the class itself rather than with instances of the class. It means that no
matter how many instances of the class there may be, there is just one property or method. Such
properties and methods are called static properties and methods.
Examples of static properties and methods in several of the intrinsic Flash Player classes are:

Math Class
This class defines a round() method. The round() method is static and is, therefore,
accessible directly from the class. For example,
trace(Math.round(1.2345));
The Math class consists entirely of static methods and constants. However, a class can have
both static and instance methods.

String Class
This class consists primarily of instance properties and methods. As the method is not associated
with any one string instance, it does not make sense to make the method an instance method.
However, it declares the method as a static method.
You can use the static attribute to declare a property or method as static. The static attribute is
always used in combination with the public, private, protected, or internal attribute. For example,
the following declares a private static property called _example.
static private var _example:String;

Singleton design pattern is one of the important uses of static properties and methods. Single design
pattern means a class having a private static property with single managed instance and public static
method that allows access to the instance.

3.5 Creating Object Instances


When an object is created, variable is declared. Thus, when a variable is declared an empty space is
created in the computers memory. An actual value must be assigned to a variable, which means you
need to create an object and store it in a variable before using or manipulating it.
An object can also be created without using ActionScript. In Flash, when a movie clip symbol or any
other symbol is placed on the stage, you can assign an instance name in the Property Inspector.
Flash then declares a variable with the same instance name and creates an object instance. You can
also create object instances using ActionScript. Using several ActionScript data types, you can create
an instance using a literal expression. Some examples are,

Literal numeric value

var someNumber:Number = 17.239;


var someNegativeInteger:int = -53;
var someUint:uint = 22;

Literal String value


var firstName:String = "Smith";
var soliloquy:String = "To be or not to be, that is the question...";

While creating an object instance, use a new operator with the class name. For example,
var myCar:MovieClip = new MovieClip();
var birthday:Date = new Date(2006, 7, 9);
When an object is created using a new operator, it is called a constructor. The constructor is the part
of a process of creating an instance of a class. When an instance is created in this way, put
parentheses after the class name. The new operator can also be used to create an instance of a
movie clip symbol that is defined in the Library, but is not placed on the Stage.

Quick Test 3.1


1.

____________________ is a technique for programming a paradigm for writing programs


for a set of problems.
WAP

PHP

CGI

Object-oriented programming

2. A package is a blueprint for an object.


True

False

3. The _____________ class defines a round() method.


Custom

String

Math

Var

3.6 Setting Classpath


The class file should be saved in a directory path corresponding to the package. If necessary, you can
add the top level directory to the classpath.
Class files should be saved in a directory path that corresponds to the class package. The compiler
looks for classes where the path corresponds to the package with the help of a classpath. The default
classpath for any Flash project includes the project directory. For example, if the com directory is
saved in the same directory as the .fla file, then the compiler will find the classes.
You can also save files in a different directory. For example, if you have a common library used by
many projects, then you can save that library in one location rather than making copies for each
project. You can add to and edit the classpath so the compiler knows where to look for all your
custom classes.
For Flash the classpath can be edited either at the project level or globally. At the project level, in the
File menu, click Publish Settings. The Publish Settings dialog box will be displayed. Now, in the
Flash tab, click the ActionScript Settings button. The ActionScript 3.0 Settings dialog box, as
shown in Figure 3.1, will be displayed.

Figure 3.1: ActionScript 3.0 Settings dialog box

At the global level, in the Edit menu, click Preferences. The Preferences dialog box will be
displayed. Now, click the ActionScript Settings button. The ActionScript 3.0 Settings dialog box,
as shown in Figure 3.2, will be displayed.

Figure 3.2: ActionScript 3.0 Settings dialog box

3.7 Inheritance Concept


To create a class that inherits from an existing class, write a subclass using the keyword extends.
The features of the new class will be similar to the existing class. However, instead of writing a new
class, you can inherit an existing class with the same functionality. Thus, the new class is called as a
subclass and the existing class is called as a super class. You can define inheritance between
classes in the subclass declaration using the extends keyword. For example,
public class Subclass extends Superclass
A subclass can call all the public and protected properties and methods of a superclass. However,
private properties and methods cannot be accessed outside the class.
Inheritance is a powerful technique. While writing a subclass, check whether the new class actually
has a subclass relationship with the existing class. There are two basic types of relationships that
classes can have inheritance and composition.
Example,
The library has different types of items such as books and DVDs. The DVDs have different types of
data associated with them. Books have page counts and authors, while DVDs might have running
times, actors, directors, and so on. However, you also want to associate certain common types of
data with both books and DVDs. For example, all library items might have Dewey decimal
classifications as well as unique identification numbers assigned by the library. And every sort of
library item has a title or name. In such a case, it can be advantageous to define a class that
generalizes the commonality of all library items.

package org.examplelibrary.collection {
public class LibraryItem {
protected var _ddc:String;
protected var _id:String;
protected var _name:String;
public function LibraryItem() {}
public function setDdc(value:String):void {
_ddc = value;
}
public function getDdc():String {
return _ddc;
}
public function setId(value:String):void {
_id = value;
}
public function getId():String {
return _id;
}
public function setName(value:String):void {
_name = value;
}
public function getName():String {
return _name;
}
}
}
Thus, you can say that books and DVDs are both types of LibraryItem.

3.8 Encapsulation and Polymorphism


The process of binding the code and data together is called encapsulation. Encapsulation hides the
functional details of a particular class from the objects that are used to send messages to it. For
example, if given an object, the user should be able to know how to use the object without
understanding the functionality of the object. This information is hidden and cannot be changed by a
user.
Polymorphism is a feature that includes a single interface and multiple methods. It means you can use
more than one kind of objects in the same context. The basic idea of polymorphism is that any class
that implements an interface looks similar to other class that implements the same interface.
Polymorphism has the ability to use a single method name for a method that behaves differently when
applied to different data types.
A simple example of a base class named Shape with two subclasses named Circle and Square.
The Shape class defines a method named area(), which returns the area of the shape. If
polymorphism is implemented, then the area() method can be called on objects of type Circle
and Square and have the correct calculations done. Inheritance enables polymorphism by allowing

subclasses to inherit and redefine, or override, methods from the base class. In the following example,
the area() method is redefined by the Circle and Square classes.
class Shape {
public function area():Number {
return NaN;
}
}
class Circle extends Shape {
private var radius:Number = 1;
override public function area():Number {
return (Math.PI * (radius * radius));
}
}
class Square extends Shape {
private var side:Number = 1;
override public function area():Number {
return (side * side);
}
}
var cir:Circle = new Circle();
trace(cir.area()); // output: 3.141592653589793
var sq:Square = new Square();
trace(sq.area()); // output: 1
As each class defines a data type, the use of inheritance creates a special relationship between a
base class and a class that extends it. A subclass is guaranteed to possess all the properties of its
base class, which means that an instance of a subclass can always be substituted for an instance of
the base class. For example, if a method defines a parameter of type Shape, it is legal to pass an
argument of type Circle because Circle extends Shape, as follows,
function draw(shapeToDraw:Shape) {}
var myCircle:Circle = new Circle();
draw(myCircle);
For detailed step-by-step procedure, from Encapsulation and Polymorphism:
eResources 4 Me>> My Varsity>> Basic Scripting and Interactivity>> Show Me How

3.9 Attaching Class to Movie Clip Symbol


The rendering model available for ActionScript 3.0 and Flash Player 9.0 is basically different from the
previous version. In the earlier version, the movie clip was the focal point of the renderer. The root
movie clip could contain child movie clips, which could, in turn, contain more child movie clips.
Methods such as createEmptyMovieClip(), attachMovie(), or duplicateMovieClip()
were used to create movie clips.
In ActinScript 3.0, the new rendering model centers on the display list concept and focuses on the
classes available in the flash.display package. The display list is a hierarchy that contains all

visible objects in the SWF movie. Any object not available in the display list is not drawn by the
renderer. Each SWF movie contains exactly one display list.
The display list consists of three types of elements.

Stage
A single stage object is available in every movie. This stage contains an entire object hierarchy of
everything displayed on the screen. A stage is a container containing the main application class of
the SWF movie and a single child. The stage can be accessed by referring to the stage property
on any display object in the display list.

Display Object Containers


A display object container is an object containing child display objects. Thus, the stage is a
display object container. Other display object containers are Sprite, MovieClip, and Shape. When
a display object container is removed from the display list, all its children are removed as well.

Display Objects
A display object is a visual element that appears on screen only after it is added into a display
object container. Some classes function as both, display objects and display object containers,
such as MovieClip, while other classes are only display objects, such as a TextField.

3.10 Extending MovieClip Class


Even a simple Flash application uses a movie clip. Creating classes that extend MovieClip can be a
very powerful and useful resource.
Earlier, custom visuals could be created by extending MovieClip. But there always had to be a
MovieClip symbol in the library linked to the ActionScript class to create an on-screen instance via
attachMovie(). A custom visual could never be entirely created in ActionScript. But the process
has been simplified with the display list model. It allows you to do everything in pure ActionScript code
in a much more instinctive manner.
In the display list model, many display classes are available. Before creating a custom visual, decide
and finalize the type. All of the available display object classes are tailored for specific purposes. So
decide what purpose does your visual class is going to serve, and then choose the appropriate parent
class based on that. By choosing the parent class carefully you can optimize size and resource
overhead.
For example, create an Abstract class which will extend the Sprite object to create functionality
from button objects. This Abstract class can then be extended to either create Standard buttons
object using the Standard class or into special buttons using the Special class.
The main file will have two movie clips including dynamic text field with an instance name txt. Place
the object on the stage. Each of these objects should have a linkage name specified using the linkage
option in the library. The structure of the files is as shown in Figure 3.3.

Figure 3.3: File structure


The Abstract class defines the basic functionality and properties for each button.
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.text.TextField;
public class AbstractButton extends Sprite {
public var _bg:Sprite;
public var _txt:TextField;
public function AbstractButton( t:String = "Abstract" ){
trace("The basic constructor function has been called");
_bg = Sprite(getChildByName("bg"));
_txt = TextField(getChildByName("txt"));
_txt.mouseEnabled = false;
// set text
setText(t);
// bg
_bg.addEventListener(MouseEvent.MOUSE_DOWN, down);
}
// sets text of button
protected function setText(t:String):void {
_txt.text = t;
}
protected function down(e:MouseEvent) {
trace(this);
_txt.textColor = 0x00CCFF;
}
}
}
The Standard class extends the Abstract class and uses the functionality defined by the main
class to create new objects. You can also add new features to the new object.
package {
import flash.text.TextField;
public class StandardButton extends AbstractButton {
private var pressed:Boolean = false;

public function StandardButton(t:String = "Standard"){


super(t);
trace("StandardButton created");
}
}
The Special class, which also extends the Abstract class, overrides the base class functionality
extending and sometimes modifying the code to fit for the current requirements.
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.text.TextField;
public class SpecialButton extends AbstractButton {
public var _star:MovieClip;
private var origX:Number;
private var pressed:Boolean = false;
public function SpecialButton(t:String = "Special"){
// must call super first
super(t);
// set star as variable
_star = MovieClip(getChildByName("star"));
trace("SpecialButton created");
}
// overriden down method
override protected function down(e:MouseEvent){
trace(this)
_txt.textColor = pressed ? 0xFFFFFF : 0xFFCC00;
_star.scaleX = _star.scaleY = pressed ? 1:0.5;
pressed = !pressed;
}
}
}

Quick Test 3.2


1. A ____________ can call all the public and protected properties and methods of a
______________.
Local, global

Subclass, super class

Math, Var

Function, String

2. Encapsulation is a process used to bind code and data together.


True
3.

False

In Flash, the _______________ class happens to be one of the key classes.


Movieclip

Method

Function

Variable

3.11 Summary
In this session, Object-Oriented Programming with ActionScript 3.0, you learned that:

Using an object-oriented approach to organize a program, you can group particular pieces of
information having common functionality.

In object-oriented programming, classes are versatile and play multiple roles.

In ActionScript 3.0, it is essential to use classes while programming.

A package is a directory that contains one or more class files and it resides in a designated
classpath directory.

A class is a blueprint for an object. It defines the object in full, that is, the data and its
operations.

A package is a way of organizing classes into groups.

In all the applications of ActionScript 3.0, class is the base.

Properties and methods are instances defined for a class.

The Math class defines a round() method.

The String class consists of instance properties and methods.

The class file should be saved in a directory path corresponding to the package.

For Flash, the classpath can be edited either at the project level or globally.

To create a class that inherits from an existing class, write a subclass using the extends
keyword.

Encapsulation is a process used to bind code and data together.

Polymorphism is a system that includes a single interface and multiple methods.

The display list consists of three types of elements. They are stage, display object containers,
and display objects.

In Flash, the MovieClip class happens to be one of the key classes.

In the display list model, many display classes are available.

3.12 Exercise
1. A _____________ is a way of organizing classes into groups.
class
project
package
program
2. The ______________ class consists entirely of static methods and constants.
Math
String
Super
Sub
3. The default Classpath for any Flash project includes the project directory.
True
False
4. A ______________ is a container containing the main application class of the SWF movie
and a single child.
package
display objects
display object containers
stage
5. Creating classes that extend MovieClip can be a very powerful and useful resource.
True
False

Se ssi on 4

Components
Learning Outcomes
In this session, you will learn to:

Capture keyboard inputs

Control mouse actions

List and describe the user interface components

In the previous session, you learned about object-oriented concept, classes, and packages. You
also learned to create properties, methods, and object instances. You became familiar with
polymorphism and encapsulation. You also learned to extend the MovieClip class. In this
session, you will learn to capture keyboard inputs. You will also learn to control the mouse actions
and become familiar with the user interface components.

4.1 Capturing User Inputs


The ability to react in response to a keyboard action is known as capturing user inputs. For this
purpose Listen for and handle key events can be used. Handling key events is similar to handling the
enterFrame event.
If a key is pressed by the user, the keyboardEvent defines a keyCode property. There is a similar
property, charCode, which contains the character code value of the key pressed or released.
Keyboard events are easy to handle. The only requirement for listening and responding to keyboard
events is that the object that receives the events must have focus. Display objects that inherit their
interaction model from the InteractiveObject class can respond to keyboard events by using event
listeners.
The following is an example of keyboard action using key events. It shows a simple class that
responds for the keyDown event by tracing the character code for that key. It also demonstrates how
to use some of the data contained in the event object passed to the handler method.
First, create a dynamic text field with its instance name as display_txt. Then, insert the following code
in the Actions panel.
import flash.events.KeyboardEvent;
stage.focus = this;
this.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
function onKeyDown(event:KeyboardEvent):void {
var temp = event.charCode;
var sValue:String = String.fromCharCode(temp);
display_txt.htmlText = "The key that was pressed is <b>"+sValue+"</b>";
}
You can see that the text field displays the alphabets pressed on the keyboard.
Taking this action on one level further, you can use the same text field as a notepad for typing
purpose. To do this, insert the following code in the Actions panel.

display_txt.border = true;
display_txt.type = "input";
display_txt.addEventListener(KeyboardEvent.KEY_DOWN,reportKeyDown);
display_txt.addEventListener(KeyboardEvent.KEY_UP,reportKeyUp);
function reportKeyDown(event:KeyboardEvent):void {
trace("Key Pressed: " + String.fromCharCode(event.charCode) + " (key code: " +
event.keyCode + " character code: " + event.charCode + ")");
if (event.keyCode == Keyboard.SHIFT) {
display_txt.borderColor = 0xFF0000;
}
}
function reportKeyUp(event:KeyboardEvent):void {
trace("Key Released: " + String.fromCharCode(event.charCode) + " (key code: "
+ event.keyCode + " character code: " + event.charCode + ")");
if (event.keyCode == Keyboard.SHIFT) {
display_txt.borderColor = 0x000000;
}
}
For detailed step-by-step procedure, refer demo Capturing User Inputs from:
eResources 4 Me>> My Varsity>> Basic Scripting and Interactivity>> Show Me How

4.2 Controlling Mouse


When a user clicks the mouse button, moves the mouse, or scrolls the mouse over an object, Flash
player sends a mouse event to all listeners. Mouse events are created on mouse clicks that can be
used to trigger interactive functionality. You can add an event listener to the Stage to listen for mouse
events that occur anywhere within the SWF file. Similarly, you can add events for moving the mouse
and scrolling it.

4.2.1 Hide and Show Mouse Arrow


ActionScript can be used to control the default mouse cursor. The custom cursor can be made and
replaced with default course graphic. This can be attained with the help of hide() and show()
methods. The hide() method will change the mouse cursor to the invisible mode. Though invisible, it
can still trigger mouse events if present on the screen. The show() method does the reverse and
displays the default mouse on the screen.
For example, to hide and show mouse arrow, create a show and hide button on the Stage with
instance names as show_btn and hide_btn. Then, insert the following code in the Actions panel.
function hideMouse(event:MouseEvent) {
trace("mouse is now invisible state");
Mouse.hide();
}
hide_btn.addEventListener(MouseEvent.CLICK, hideMouse);
function showMouse(event:MouseEvent) {
trace("mouse is now visible state");

Mouse.show();
}
show_btn.addEventListener(MouseEvent.CLICK, showMouse);
On publishing the file you can see that the cursor disappears when clicked on the hide button and
becomes visible when the show button is clicked.

4.2.2 Creating Custom Mouse Arrow


The mouse cursor can be moved to any display object available on the Stage. By replacing the
standard pointer with the one designed in Flash, you can integrate the user's mouse movement within
the SWF file more closely. To create a custom pointer, you can design your own customize pointer
movie clip on the Stage. Then, in ActionScript, hide the standard pointer and track its movement. To
hide the standard pointer, use the hide() method from the built-in Mouse class.
The following example illustrates a basic execution of this task. Create a movie clip, then from the
library right-click over the movie clip and click Linkage. The Linkage Properties dialog box, as
shown in Figure 4.1, will be displayed.

Figure 4.1: Linkage Properties dialog box


Now, click OK and then add the following code in the Actions panel.
import flash.ui.Mouse;
import flash.events.*;
var cursor:prince = new prince();
this.addChild(cursor);
Mouse.hide();
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
stage.addEventListener(MouseEvent.MOUSE_OVER, mouseMoveHandler);
stage.addEventListener(MouseEvent.MOUSE_OUT, mouseMoveHandler);
function mouseMoveHandler(event:MouseEvent):void {
cursor.x = event.localX;
cursor.y = event.localY;
event.updateAfterEvent();
}

4.2.3 Drag and Drop Objects using Mouse


You can begin building user interface components by using Sprite class as the display object. This
object is light and does not make use of any frames and associated overhead. It provides drag-anddrop support and acts as a DropTarget for other DisplayObjects. It also has a button mode
property and extends the DisplayObjectContainer and contains all the associated methods of
that class.
Dragging support in particular sets the Sprite class apart from its superclass and makes it a great
candidate to build the moveable parts of a UI component with. To provide a drag-and-drop style
interface, use startDrag(), stopDrag(), and dropTarget from the Sprite class.
The startDrag() method can be called on any Sprite instance. It follows the mouse and creates
the dragging effect. To stop dragging, call the stopDrag() method on the Sprite instance. After
the drag operation is complete, you can examine the dropTarget property of the Sprite to
determine the object that the Sprite was dropped on. The value of dropTarget is useful for
determining if a drop operation is valid.
For example, create a movie clip and enter the instance name as Oval_mc. Then, insert the following
code in the Actions panel.
Oval_mc.addEventListener(MouseEvent.MOUSE_DOWN,DragStart);
Oval_mc.addEventListener(MouseEvent.MOUSE_UP,DragStop);
function DragStart(event:Event) {
trace("Drag Started!");
event.target.startDrag(false);
}
function DragStop(event:Event) {
trace("Drag Stoped!");
event.target.stopDrag();
}
You can see that the movie clip can be dragged and dropped to any part of the work area.
For detailed step-by-step procedure, refer demo Controlling Mouse from:
eResources 4 Me>> My Varsity>> Basic Scripting and Interactivity>> Show Me How

4.3 Using Components


By using components you can quickly and easily build a robust Flash application with consistent
behavior and appearance. Instead of creating and programming these symbols, you can use the
readily available components. Simply drag these components from the Components panel into your
application. You can also customize the look and feel of these Components in order to meet your
requirements.
With the help of components, you can separate the process of designing the application and coding.
Components allow the developers to create functionality that designers can use in the applications.
Each component has a unique set of ActionScript methods, properties, and events that make up its
application-programming interface. The API allows you to create and manipulate components while
the application is running.

4.3.1 Types of Components


The frequently used functionality can be encapsulated into components and designers can customize
these components by changing their parameters. They can also change the appearance of the
component by editing its graphical elements. Components share core functionality such as styles,
skins, and focus management. ActionScript 3.0 components include three categories of components.
Refer to Table 4.1.

Button

List

TextArea

CheckBox

NumericStepper

TextInput

ColorPicker

RadioButton

TileList

ComboBox

ProgressBar

UILoader

DataGrid

ScrollPane

UIScrollBar

Label

Slider

Table 4.1: User interface components


To open Flash components, on the Window menu, click Components. The Components panel will
be displayed. Refer to Figure 4.2.

Figure 4.2: Components panel

4.3.2 User Interface Components


Flash components are pieces of advanced flash work, which extends Flash functionality to enable fast
integration catering the needs of a beginner to advanced level users.
The common user interface components in Flash are:

Buttons
For any Web applications or forms, button is a basic requirement. To add button to a new
Flash file ActionScript 3.0 document, drag the Button component from the Components
panel to the current document's Library panel. Then, open the Actions panel, select Frame
1 in the main Timeline and enter the following code to create a button instance:

import fl.controls.Button;
var myButton:Button = new Button();
addChild(myButton);
myButton.label = "Submit Form";
myButton.toggle = true;
myButton.move(50, 50);
Next, add the following ActionScript to create an event listener and an event handler function.
myButton.addEventListener(MouseEvent.CLICK, clickHandler);
function clickHandler(event:MouseEvent):void {
trace("Event type: " + event.type);
}
Now, you can check if the button functions properly by clicking the Control menu and selecting
Test Movie.

CheckBox
A CheckBox component is a square box that can be selected or cleared. It is mostly used to
check user response or while creating assessments. When it is selected a check mark
appears in the box. You can add a text label to the CheckBox component and place it to the
right, left, above, or below it. For example, drag four CheckBox components from the
Components panel to the Stage. Then, in the Property Inspector, enter the instance names
as box_01, box_02, box_03, and box_04. Now, enter the options name in the label
parameter and place a Submit button on Stage to validate the option with an instance name
as submit_btn. Create an empty dynamic text field with an instance name as display_txt.
Then, in the Actions panel, select Frame 1 in the main Timeline, and enter the following
ActionScript code:

var UserArray:Array = new Array();


var correctArray:Array = ["Punjabi","Hindi"];
box_01.addEventListener(MouseEvent.CLICK,fnUpdateArray);
box_02.addEventListener(MouseEvent.CLICK,fnUpdateArray);
box_03.addEventListener(MouseEvent.CLICK,fnUpdateArray);
box_04.addEventListener(MouseEvent.CLICK,fnUpdateArray);
submit_btn.addEventListener(MouseEvent.CLICK,quizValidate);
function fnUpdateArray(e:MouseEvent) {
var sName:String;
var sIndex:Number;
var ArrayHolder:Number;
sName = e.target.name;
sIndex = sName.lastIndexOf("_0");
ArrayHolder = Number(sName.substring(sIndex+2))-1;
if (e.target.selected == true) {
UserArray[ArrayHolder] =e.target.label;
} else {
UserArray[ArrayHolder] ="";
}
}
function quizValidate(event:MouseEvent) {
var TempArray:Array = new Array();
for (var i =0; i<5; i++) {
if (UserArray[i] != "" ) {
TempArray.push(UserArray[i]);
}
}
for (var j =0; j<correctArray.length; j++) {
if (TempArray[j] == correctArray[j]) {
display_txt.htmlText = "<b> That's Correct.</b>";
} else {
display_txt.htmlText = "<b> That's Incorrect.</b>";
}
}
disableAll();
}
function disableAll() {
box_01.enabled = false;
box_02.enabled = false;
box_03.enabled = false;
box_04.enabled = false;
submit_btn.enabled = false;
}

Now, on the Control menu, click Test Movie. You can see that a simple check box assessment
is created.

ComboBox
This component allows the user to make a single selection from the drop-down list. To add a
combo box to a new Flash file, drag the ComboBox component to the Stage and give it an
instance name as comb_01.
On the Parameters tab, with the ComboBox component selected on the Stage, click the
DataProvider cell. Then, click the magnifying glass icon. The Values dialog box, as shown in
Figure 4.3, will be displayed.

Figure 4.3: Values dialog box


Set the options such as French, Punjabi, German, and Hindi. Then, place a Submit button on
Stage to validate the option with an instance name as submit_btn. Create an empty dynamic
text field with an instance name as display_txt. Now, open the Actions panel, select Frame
1 in the main timeline, and enter the following code:
Now, on the Control menu, click Test Movie. You can see that a simple combo box
assessment is created.
var UserAnswer:String;
var correctAnswer:String = "Hindi";
comb_01.addEventListener(Event.CHANGE,fnUpdateArray);
submit_btn.addEventListener(MouseEvent.CLICK,quizValidate);
function fnUpdateArray(e:Event) {
UserAnswer = e.target.selectedItem.label;
}
function quizValidate(event:MouseEvent) {
if (UserAnswer == correctAnswer) {
display_txt.htmlText = "<b> That's Correct.</b>";
} else {
display_txt.htmlText = "<b> That's Incorrect. The correct answer is
Hindi.</b>";
}
disableAll();
}

function disableAll() {
comb_01.enabled = false;
submit_btn.enabled = false;
}

RadioButton
This component can be used when the user has to make a single choice within a set of
choices. It should be used in a group of at least two RadioButton instances. A radio button
is a fundamental part of many form applications on the Web.
To add radio buttons in a new Flash file, drag three RadioButton components from the
Components panel to the Stage and enter the instance names as box_01, box_02, and
box_03. Now, place a Submit button on Stage to validate the option with an instance name
as submit_btn. Create an empty dynamic text field with an instance name as display_txt.
Then, open the Actions panel, select Frame 1 in the main Timeline, and enter the following
code:

var UserOption:String;
var correctAnswer:String = "Three";
box_01.addEventListener(MouseEvent.CLICK,fnUpdateArray);
box_02.addEventListener(MouseEvent.CLICK,fnUpdateArray);
box_03.addEventListener(MouseEvent.CLICK,fnUpdateArray);
submit_btn.addEventListener(MouseEvent.CLICK,quizValidate);
function fnUpdateArray(e:MouseEvent) {
if (e.target.selected == true) {
UserOption =e.target.label;
}
}
function quizValidate(event:MouseEvent) {
if (UserOption == correctAnswer) {
display_txt.htmlText = "<b> That's Correct.</b>";
} else {
display_txt.htmlText = "<b> That's Incorrect. The correct answer is
Three.</b>";
}
disableAll();
}
function disableAll() {
box_01.enabled = false;
box_02.enabled = false;
box_03.enabled = false;
submit_btn.enabled = false;
}
You can see that a radio button assessment is created.

ScrollPane
This component can be used to display content that is too large for the area into which it is
loaded. For example, if you have a large image and only a small space for it in an application,
you could load it into a scroll pane.
To add scroll pane to a new Flash file, drag the ScrollPane component from the
Components panel to the Stage and give it an instance name as myScrollPane. Then, open
the Actions panel, select Frame 1 in the main Timeline, and enter the following ActionScript
code. Ensure that the image called in the scroll pane is placed in the given folder.

import fl.events.ScrollEvent;
myScrollPane.setSize(300, 200);
function scrollListener(event:ScrollEvent):void {
trace("horizontalScPosition: " + myScrollPane.horizontalScrollPosition + ",
verticalScrollPosition = " + myScrollPane.verticalScrollPosition);
};
myScrollPane.addEventListener(ScrollEvent.SCROLL, scrollListener);
function completeListener(event:Event):void {
trace(event.target.source + " has completed loading.");
};
// Add listener
myScrollPane.addEventListener(Event.COMPLETE, completeListener);
myScrollPane.source = " images/image1.jpg";
Now, on the Control menu, click Test Movie to run the application.
For detailed step-by-step procedure, refer demo Components from:
eResources 4 Me>> My Varsity>> Basic Scripting and Interactivity>> Show Me How

FLVPlayback
This component allows you to include a video player in the Flash CS3 Professional
application. It plays progressively downloaded Adobe Flash Video (FLV) files over HTTP or
play streaming FLV files from Adobe's Macromedia Flash Media Server.
To add this component, in the Components panel, click the plus (+) button to open the video
entry and drag the FLVPlayback component to the Stage. With the FLVPlayback component
selected on the Stage, locate the Value cell for the source parameter on the Parameters tab
of the Component Inspector, and enter a string that specifies one of the following:

A local path to an FLV file

An URL to an FLV file

An URL to a synchronized Multimedia Integration Language (SMIL) file that describes


how to play an FLV file

Now, on the Parameters tab, with the FLVPlayback component selected on the Stage, click
the Value cell for the Skin parameter. Click the Magnifying Glass icon. The Select Skin
dialog box, will be displayed. Refer to Figure 4.4.

Figure 4.4: Select Skin dialog box


The Skin list provides various options as follows:

Select one of the pre-designed skins to attach a set of playback controls to the component.

Select Custom Skin URL from the pop-up menu if you have created a custom skin. Next,
enter the URL for the SWF file that contains the skin in the URL box.

Select None and drag individual FLV Playback Custom UI components to the Stage to add
playback controls.

Next, click OK to close the Select Skin dialog box. To execute the SWF file and start the video,
on the Control menu, click Test Movie.

Setting FLVPlayback Component Parameters


To add a FLVPlayback component, drag it on the Stage. Then, you need to specify the file
that has to be played. You can also set various parameters that govern its behavior and
describe the FLV file.
For each instance of the FLVPlayback component, the following parameters can be set in the
Component Inspector or the Property Inspector: align, autoPlay, cuePoints, preview,
scaleMode, skin, skinAutoHide, skinBackgroundAlpha, skinBackgroundColor, source,
and volume. Each of these parameters has a corresponding ActionScript property of the
same name. When you assign a value to these parameters you are setting the initial state of
the property in the application.
You can specify the name and location of the FLV file in the source parameter. Double-click
the Value cell to open the Content Path dialog box as shown in Figure 4.5.

Figure 4.5: Content Path dialog box

In the Content Path dialog box, click the icon folder to browse the exact location.
The Match source FLV dimensions option specifies whether the FLVPlayback instance on
the Stage should match the dimensions of the source FLV file.
The Download FLV for cue points and dimensions check box is enabled only if the
content path is HTTP or RTMP URL, which means the FLV file is not local. This option
specifies whether to download or stream a portion of the FLV file to acquire the FLV file
dimensions and any cue point definitions that are embedded within it. Flash uses the
dimensions to resize the FLVPlayback instance, and it loads the cue point definitions into the
cuePoints parameter in the Component Inspector.
For each instance of the FLVPlayback component, you can set the following parameters in
the Parameters tab. Refer to Figure 4.6.

Figure 4.6: Parameters tab


Some of the important parameters are listed below:

align: Specifies the video layout when the scaleMode property is set to
VideoScaleMode.MAINTAIN_ASPECT_RATIO. The video dimensions are based on the
registrationX, registrationY, registrationWidth, and registrationHeight properties.
When you set the align property, values come from the VideoAlign class. The default is
VideoAlign.CENTER.

autoPlay: Specifies a boolean value that determines how to play the FLV file. If true, the
component plays the FLV file immediately when it is loaded. If false, the component
loads the first frame and pauses.

cuePoints: Specifies an array that describes ActionScript cue points and disabled
embedded FLV file cue points. This property is created specifically for use by the
Component Inspector and Property Inspector. It does not work if it is set in any other
way. Its value has an effect only on the first FLV file loaded and only if it is loaded by
setting the source property in the Component Inspector or Property Inspector.

scaleMode: Specifies how the video will resize after loading. If set to
VideoScaleMode.MAINTAIN_ASPECT_RATIO, the video aspect ratio within the
rectangle defined by registrationX, registrationY, registrationWidth, and
registrationHeight is maintained.

Skin: Specifies the URL to a skin SWF file. It is a string that contains a file name, a
relative path, such as Custom_Skin.swf, or an absolute URL.

skinAutoHide: It is a boolean value that, if true, hides the component skin when the
mouse is not over the video. This property affects only skins that are loaded by setting the
skin property and not a skin that you create from the FLVPlayback Custom UI
components. When the component is in full-screen takeover mode and the skin is one

that does not lay over the video, then skinAutoHide mode is turned on automatically. If
the property is set to false after entering full-screen mode then it overrides the behavior.

skinBackgroundAlpha: This property works only with SWF files that have skins loaded
by using the skin property and with skins that support setting the color and alpha. You
can set this property to a number between 0.0 and 1.0. The default is .85.

skinBackgroundColor: This property works only with SWF files that have skins loaded
in the components. The skin property contains different settings. The default is the last
value chosen by the user as the default.

Source: Specifies the URL of the FLV file that has to be streamed. The URL could be
HTTP URL to an FLV file, RTMP URL to a stream, or HTTP URL to an XML file.
If this property is set through the Property Inspector, then the FLV file begins loading
and playing at the next "enterFrame" event. The delay provides time to set the isLive,
autoPlay, and cuePoints properties, among others, which affect loading. It also allows
ActionScript that is placed on the first frame to affect the FLVPlayback component before
it starts playing.
If this property is set through ActionScript, then it immediately calls the
VideoPlayer.load() method when the autoPlay property is set to false; else, it calls
the VideoPlayer.play() method. The autoPlay, totalTime, and isLive properties
affect how the new FLV file is loaded, so if you set these properties, you must set them
before setting the source property.
Set the autoPlay property to false to prevent the new FLV file from playing automatically.

Volume: Specifies a number in the range of 0 to 1 indicating the volume control settings.

Quick Test 4.1


1. If a key is pressed by the user, the KeyboardEvent defines a _______________
property.
charCode

keyCode

charEvent

keyDown

2. _____________ can be used to control the default mouse cursor.


Mouse trail

Mouse call

Mouse hold

ActionScript

3. Components combine the process of designing the application and coding.


(True/False)
True

False

4.4 Summary
In this session, Components, you learned that:

The ability to react in response to a keyboard action is known as capturing user inputs.

If the user presses a key, the KeyboardEvent defines a keyCode property.

When a user clicks the mouse button, moves the mouse, or scrolls the mouse over an object,
Flash player sends a mouse event to all listeners.

The custom cursor can be made and replaced with default course graphic. This can be
attained with the help of hide() and show() methods.

To create a custom pointer, you can design your own customize pointer movie clip on the
Stage.

To hide the standard pointer, use the hide() method from the built-in Mouse class.

You can begin building user interface components by using the Sprite class as the display
object.

The startDrag() method can be called on any Sprite instance.

Using components you can quickly and easily build a robust Flash application with consistent
behavior and appearance.

Each component has a unique set of ActionScript methods, properties, and events that make
up its application programming interface.

The ComboBox component allows the user to make a single selection from the drop-down list.

The RadioButton component can be used when the user has to make a single choice
within a set of choices.

The ScrollPane component can be used to display content that is too large for the area into
which it is loaded.

The FLVPlayback component allows you to include a video player in the Flash CS3
Professional application.

For each instance of the FLVPlayback component, the align, autoPlay, cuePoints,
preview, scaleMode, skin, skinAutoHide, skinBackgroundAlpha, skinBackgroundColor,
source, and volume parameters can be set in the Component Inspector or the Property
Inspector.

4.5 Exercise
1. The _______________ property returns the character code value of the key pressed or
released by the user.
keyCode
keyDown
charCode
charEvent
2. To hide the standard pointer, use the hide() method of the built-in Mouse class.
MouseEvent
Mouse
Sprite
InteractiveObject
3. The API allows you to create and manipulate components while the application is running.
True
False
4. The _________________ component allows the user to make a single selection from the
drop-down list.
Check Box
Radio Button
Scroll Pane
Combo Box
5. Which of the following component allows including a video player in the Flash CS3
Professional application?
FLVPlayback
ScrollPane
RadioButton
ComboBox

Answer Key
Quick Answers

Exercise Answers

Quick Test 1.1


2. False

1. Actions
3. trace()

Quick Test 1.2


2. MovieClip

1. Objects
3. False

Quick Test 1.3


1. Boolean values
3. True

2. True
Quick Test 2.2

1. Date()
3. flash.display.loader

1. Script Navigator

2. Operators

3. False

4. nextScene()

5. True

6. mouseMove

7. True

8. sort()
Exercise 2.8

2. Associative

Quick Test 2.1


1. if

Exercise 1.11

2. False

1. showMessage()

2. removeChild()

3. True

4. NONE

5. False

6. fullYear

7. SharedObject.flush()
Exercise 3.12

Quick Test 3.1


1. Object-oriented
programming

2. False

1. package

2. Math

3. True

4. stage

3. Math
5. True
Quick Test 3.2
1. Subclass, super
class

Exercise 4.5
2. True

1. charCode

2. Mouse

3. True

4. Combo Box

3. Movieclip
Quick Test 4.1
1. keyCode
3. False

2. ActionScript

5. FLVPlayback

You might also like