Example: Creating a basic application. Adobe Flex, FLEX 2-PROGRAMMING ACTIONSCRIPT 3.0
Below you will find brief information for ActionScript 3.0 Programming. This manual provides a foundation for developing applications in ActionScript 3.0, covering core concepts such as language syntax, object-oriented programming, and the Flash Player API. Learn about event handling, networking, and more to build robust and interactive applications.
Advertisement
Advertisement
■ ActionScript class definition: a definition of an ActionScript class, including its method and property definitions.
When you define a class, you can access the ActionScript code in the class by creating an instance of the class and using its properties, methods, and events, just as you would with any of the built-in ActionScript classes. This requires two parts:
■
Use the import statement to specify the full name of the class, so the ActionScript compiler knows where to find it. For example, if you want to use the MovieClip class in ActionScript, you first need to import that class using its full name, including package and class: import flash.display.MovieClip;
Alternatively, you can import the package that contains the MovieClip class, which is equivalent to writing separate import statements for each class in the package: import flash.display.*;
■
The only exceptions to the rule that a class must be imported in order to refer to that class in your code are the top-level classes which are not defined in a package.
Write code which specifically refers to the class name (usually declaring a variable with that class as its data type, and creating an instance of the class to store in the variable).
By referring to another class name in ActionScript code, you tell the compiler to load the definition of that class. For example, given an external class called Box, this statement causes a new instance of the Box class to be created: var smallBox:Box = new Box(10,20);
When the compiler comes across the reference to the Box class for the first time, it searches the loaded source code to locate the Box class definition.
Example: Creating a basic application
You can create external ActionScript source files with an .as extension using Flash, Flex
Builder, Dreamweaver, or any text editor.
ActionScript 3.0 can be used within a number of application development environments, including the Flash authoring and Flex Builder tools.
This section walks through the steps in creating and enhancing a simple ActionScript 3.0 application using the Flash authoring tool or the Flex Builder 2 tool. The application you’ll build presents a simple pattern for using external ActionScript 3.0 class files in Flash and Flex applications. That pattern will apply to all of the other example applications in this book.
26 Getting Started with ActionScript
Designing your ActionScript application
You should have some idea about the application you want to build before you start building it.
The representation of your design can be as simple as the name of the application and a brief statement of its purpose, or as complicated as a set of requirements documents containing numerous Unified Modeling Language (UML) diagrams. This book doesn’t discuss the discipline of software design in detail, but it’s important to keep in mind that application design is an essential step in the development of ActionScript applications.
Our first example of an ActionScript application will be a standard “Hello World” application, so its design is very simple:
■
■
■
■
The application will be called HelloWorld.
It will display a single text field containing the words “Hello World!”
In order to be easily reused, it will use a single object-oriented class, named Greeter, which can be used from within a Flash document or a Flex application.
After you create a basic version of the application, you will add new functionality to have the user enter a user name and have the application check the name against a list of known users.
With that concise definition in place, you can start building the application itself.
Creating the HelloWorld project and the Greeter class
The design statement for the Hello World application said that its code should be easy to reuse. With this goal in mind, the application uses a single object-oriented class, named
Greeter, which is used from within an application that you create in Flex Builder or the Flash authoring tool.
To create the HelloWorld project and Greeter class in Flex Builder:
1.
In Flex Builder, select File > New> Flex Project,
2.
If the New Flex Project dialog box asks you to select a Flex Server Technology, select Basic, and then click Next.
3.
Type HelloWorld as the Project Name, and then click Finish.
Your new project will be created and should be showing in the Navigator panel. By default the project should already contain a file named HelloWorld.mxml, and that file should be open in the Editor panel.
4.
Now to create a custom ActionScript class file in the Flex Builder tool, select File > New >
ActionScript File.
Example: Creating a basic application 27
5.
In the New ActionScript File dialog box, select HelloWorld as the parent folder, type
Greeter.as
the filename, and then click Finish.
A new ActionScript editing window is displayed.
Continue with “Adding code to the Greeter class” on page 28 .
Adding code to the Greeter class
The Greeter class defines an object, Greeter , that you will be able to use in your HelloWorld application.
To add code to the Greeter class:
1.
Type the following code into the new file: package
{ public class Greeter
{ public function sayHello():String
{ var greeting:String; greeting = "Hello World!"; return greeting;
}
}
}
2.
The Greeter class includes a single sayHello() method , which returns a string that says
“Hello” to the user name that is given.
Select File > Save to save this ActionScript file.
The Greeter class is now ready to be used in a Flash or Flex application.
Creating an application that uses your ActionScript code
The Greeter class that you have built defines a self-contained set of software functions, but it does not represent a complete application. To use the class, you need to create a Flash document or Flex application.
The HelloWorld application creates an new instance of the Greeter class. Here’s how to attach the Greeter class to your application.
28 Getting Started with ActionScript
To create an ActionScript application using Flex Builder:
1.
Open the HelloWorld.mxml file, and type the following code:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*" layout="vertical" creationComplete = "initApp()" >
<mx:Script>
<![CDATA[ private var myGreeter:Greeter = new Greeter(); public function initApp():void
{
// says hello at the start, and asks for the user's name mainTxt.text = myGreeter.sayHello();
}
]]>
</mx:Script>
<mx:TextArea id = "mainTxt" width="400" />
</mx:Application>
2.
This Flex project includes three MXML tags:
■
■
An <mx:Application> tag, which defines the Application container
An <mx:Script> tag that includes some ActionScript code
■
An <mx:TextArea> tag, which defines a field to display text messages to the user
The code in the <mx:Script> tag defines a initApp() method that is called when the application loads. The initApp() method sets the text value of the mainTxt TextArea to the “Hello World!” string returned by the sayHello() method of the custom class
Greeter, which you just wrote.
Select File > Save to save the application.
Continue with “Publishing and testing your ActionScript application” on page 30 .
Example: Creating a basic application 29
Publishing and testing your ActionScript application
Software development is an iterative process. You write some code, try to compile it, and edit the code until it compiles cleanly. You run the compiled application, test it to see if it fulfills the intended design, and if it doesn’t, you edit the code again until it does. The Flash and Flex
Builder development environments offer a number of ways to publish, test, and debug your applications.
Here are the basic steps for testing the HelloWorld application in each environment.
To publish and test an ActionScript application using Flex Builder:
1.
Select Run > Run. Make sure that the Project field shows “HelloWorld” and the
Application file field shows “HelloWorld.mxml”.
2.
In the Run dialog box, click Run.
The HelloWorld application starts.
■
■
If any errors or warnings are displayed in the Output window when you test your application, fix the causes of these errors in the HelloWorld.mxml or Greeter.as files, and then try testing the application again.
If there are no compilation errors, a browser window opens showing the Hello World application. The text “Hello World!” should be displayed.
You have just created a simple but complete object-oriented application that uses ActionScript
3.0. Continue with “Enhancing the HelloWorld application” on page 30 .
Enhancing the HelloWorld application
To make the application a little more interesting, you’ll now make it ask for and validate a user name against a predefined list of names.
First, you will update the Greeter class to add new functionality. Then you will update the
Flex or Flash application to use the new functionality.
To update the Greeter.as file:
1.
Open the Greeter.as file.
30 Getting Started with ActionScript
2.
Change the contents of the file to the following (new and changed lines are shown in boldface): package
{ public class Greeter
{
/**
* Defines the names that should receive a proper greeting.
*/ public static var validNames:Array = ["Sammy", "Frank", "Dean"];
/**
* Builds a greeting string using the given name.
*/ public function sayHello( userName:String = "" ):String
{ var greeting:String; if (userName == "")
{ greeting = "Hello. Please type your user name, and then press the Enter key.";
} else if (validName(userName))
{ greeting = "Hello, " + userName + ".";
} else
{ greeting = "Sorry, " + userName + ", you are not on the list.";
} return greeting;
}
}
}
/**
* Checks whether a name is in the validNames list.
*/ public static function validName(inputName:String = ""):Boolean
{ if (validNames.indexOf(inputName) > -1)
{ return true;
} else
{ return false;
}
}
Example: Creating a basic application 31
The Greeter class now has a number of new features:
■
The validNames array lists valid user names. The array is initialized to a list of three names when the Greeter class is loaded.
■
■
The sayHello() method now accepts a user name and changes the greeting based on some conditions. If the userName is an empty string ( "" ), the greeting property is set to prompt the user for a name. If the user name is valid, the greeting becomes "Hello, userName .” Finally, if either of those two conditions are not met, the greeting variable is set to "Sorry, userName , you are not on the list."
The validName() method returns true if the inputName is found in the validNames array, and false if it is not found. The statement validNames.indexOf(inputName) checks each of the strings in the validNames array against the inputName string. The
Array.indexOf() method returns the index position of the first instance of an object in an array, or the value -1 if the object is not found in the array.
Next you will edit the Flash or Flex file that references this ActionScript class.
To modify the application using Flex Builder:
1.
Open the HelloWorld.mxml file.
2.
Next modify the <mx:TextArea> tag to indicate to the user that is is for display only, by changing the background color to a light gray and preventing the user from editing the displayed text:
<mx:TextArea id = "mainTxt" width="400" backgroundColor="#DDDDDD" editable="false" />
3.
Now add the following lines right after the <mx:TextArea> closing tag. These lines create a new TextInput field that lets the user enter a user name value:
<mx:HBox width="400">
<mx:Label text="User Name:"/>
<mx:TextInput id="userNameTxt" width="100%" enter="mainTxt.text = myGreeter.sayHello(userNameTxt.text);" />
</mx:HBox>
The enter attribute specifies that when the user presses the Enter key in the userNameTxt field, the text in the field will be passed to the Greeter.sayHello() method, and the greeting displayed in the mainTxt field will change accordingly.
The final contents of the HelloWorld.mxml file should look like this:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*" layout="vertical" creationComplete = "initApp()" >
<mx:Script>
<![CDATA[
32 Getting Started with ActionScript
private var myGreeter:Greeter = new Greeter(); public function initApp():void
{
// says hello at the start, and asks for the user's name mainTxt.text = myGreeter.sayHello();
}
]]>
</mx:Script>
<mx:TextArea id = "mainTxt" width="400" backgroundColor="#DDDDDD" editable="false" />
<mx:HBox width="400">
<mx:Label text="User Name:"/>
<mx:TextInput id="userNameTxt" width="100%" enter="mainTxt.text = myGreeter.sayHello(userNameTxt.text);" />
</mx:HBox>
</mx:Application>
4.
Save the edited HelloWorld.mxml file. Select File > Run to run the application.
When you run the application, you will be prompted to enter a user name. If it is valid
(Sammy, Frank, or Dean), the application will display the “ Hello, userName ” confirmation message.
Running subsequent examples
Having developed and run the “Hello World” ActionScript 3.0 application, you should have the basic knowledge you need to run the other code examples presented in this book.
Subsequent code examples will not be presented in a step-by-step tutorial format as this one was. The relevant ActionScript 3.0 code in each example will be highlighted and discussed, but instructions about running the examples in specific development environments won’t be provided. However the example files distributed with this book will include all of the files you need to compile and run the examples easily in your chosen development environment.
Example: Creating a basic application 33
34 Getting Started with ActionScript
Download
Advertisement
Key features
Comprehensive guide to ActionScript 3.0
Covers core language features and Flash Player APIs
Numerous code examples and sample applications
Explains object-oriented programming concepts
Detailed explanation of event handling and networking
Frequently asked questions
ActionScript 3.0 offers performance improvements (up to ten times faster), a more robust programming model, an improved API, and features like E4X for XML manipulation and native regular expressions.
ActionScript 3.0 uses run-time exceptions to report errors, providing stack traces for easier debugging and enabling robust error handling in applications.
The API includes classes like Sprite and Shape for working with visual elements, providing more control and dynamic re-parenting capabilities. Depth management is automatic.
ActionScript 3.0 uses ECMAScript for XML (E4X), making XML manipulation more intuitive and efficient through native language constructs.