View comments | RSS feed

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 sample applications in this manual.

Subtopics

Designing your ActionScript application
Creating the HelloWorld project and the Greeter class
Adding code to the Greeter class
Creating an application that uses your ActionScript code
Publishing and testing your ActionScript application
Enhancing the HelloWorld application

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 manual 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:

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 Greeter class in the Flash authoring tool:

  1. In the Flash authoring tool, select File > New.
  2. In the New Document dialog box, select ActionScript file, and click OK.

    A new ActionScript editing window is displayed.

  3. Select File > Save. Select a folder to contain your application, name the ActionScript file Greeter.as, and then click OK.

    Continue with Adding code to the Greeter class.

Adding code to the Greeter class

The Greeter class defines an object, Greeter, that you will be able to use in your HelloWorld application.

To add code to the Greeter class:

  1. Type the following code into the new file:
    package 
    {
        public class Greeter 
        {
            public function sayHello():String 
            {
                var greeting:String;
                greeting = "Hello World!";
                return greeting;
            }
        }
    }
    

    The Greeter class includes a single sayHello() method, which returns a string that says "Hello World!". <updated: 9/5/2007>

  2. Select File > Save to save this ActionScript file.

The Greeter class is now ready to be used in a Flash or Flex application.

Creating an application that uses your ActionScript code

The Greeter class that you have built defines a self-contained set of software functions, but it does not represent a complete application. To use the class, you need to create a Flash document or Flex application.

The HelloWorld application creates an new instance of the Greeter class. Here's how to attach the Greeter class to your application.

To create an ActionScript application using the Flash authoring tool:

  1. Select File > New.
  2. In the New Document dialog box, select Flash Document, and click OK.

    A new Flash window is displayed.

  3. Select File > Save. Select the same folder that contains the Greeter.as class file, name the Flash document HelloWorld.fla, and click OK.
  4. In the Flash Tools palette, select the Text tool, and drag across the Stage to define a new text field, approximately 300 pixels wide and 100 pixels high.
  5. In the Properties window, with the text field still selected on the Stage, set the text type to Dynamic Text and type mainText as the instance name of the text field. <updated: 5/1/2007>
  6. Click the first frame of the main timeline.
  7. In the Actions panel, type the following script: <code updated: 5/1/2007>
    var myGreeter:Greeter = new Greeter();
    mainText.text = myGreeter.sayHello();
    
  8. Save the file.

Continue with Publishing and testing your ActionScript application.

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 the Flash authoring tool:

  1. Publish your application and watch for compilation errors. In the Flash authoring tool, select Control > Test Movie to compile your ActionScript code and run the HelloWorld application.
  2. 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.fla or HelloWorld.as files, and then try testing the application again.
  3. If there are no compilation errors, you will see a Flash Player window showing the Hello World application. <updated this step: 5/9/2007>

You have just created a simple but complete object-oriented application that uses ActionScript 3.0. Continue with Enhancing the HelloWorld application.

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.
  2. Change the contents of the file to the following (new and changed lines are shown in boldface): <code updated: 9/5/2007>
    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;
                }
            }
        }
    }
    

    The Greeter class now has a number of new features:

  3. The validNames array lists valid user names. The array is initialized to a list of three names when the Greeter class is loaded.
  4. <updated: 9/5/2007>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."
  5. 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 the Flash authoring tool:

  1. Open the HelloWorld.fla file.
  2. Modify the script in Frame 1 so that an empty string ("") is passed to the Greeter class's sayHello() method:
    var myGreeter:Greeter = new Greeter();
    mainText.text = myGreeter.sayHello("");
    
  3. Select the Text tool in the Tools palette, and then create two new text fields on the Stage, side-by-side and directly under the existing mainText text field.
  4. In the first new text field, type the text User Name: to serve as a label.
  5. Select the other new text field, and in the Property inspector, select InputText as the type of text field. Select Single line as the Line type. Type textIn as the instance name.
  6. [updated this step; 6/22/2007]
  7. Click the first frame of the main timeline.
  8. In the Actions panel, add the following lines to the end of the existing script: <code updated: 6/22/2007>
    mainText.border = true;
    textIn.border = true;
    
    textIn.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed); 
    
    function keyPressed(event:KeyboardEvent):void 
    {
        if (event.keyCode == Keyboard.ENTER)
        {
            mainText.text = myGreeter.sayHello(textIn.text);
        }
    } 
    

    The new code adds the following functionality:

  9. The first two lines simply define borders for two text fields.
  10. An input text field, such as the textIn field, has a set of events that it can dispatch. The addEventListener() method lets you define a function that runs when a type of event occurs. In this case, that event is the pressing of the Enter key on the keyboard.
  11. The keyPressed() custom function calls the sayHello() method of the myGreeter object, passing the text from the textIn text field as a parameter. That method returns a string greeting based on the value passed in. The returned string is then assigned to the text property of the mainText text field.

    The complete script for Frame 1 is the following: <code updated: 6/22/2007>

    mainText.border = true;
    textIn.border = true;
    
    var myGreeter:Greeter = new Greeter();
    mainText.text = myGreeter.sayHello("");
    
    textIn.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
    
    function keyPressed(event:KeyboardEvent):void
    {
        if (event.keyCode == Keyboard.ENTER)
        {
            mainText.text = myGreeter.sayHello(textIn.text);
        }
    }
    
  12. Save the file.
  13. Select Control > Test Movie 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 displays the "hello" confirmation message.


Flash CS3


Comments


padrepio said on Aug 28, 2007 at 9:26 AM :
The example works, but only once. Any subsequent attempts at entering a user name fails to recognize the user as a valid user. This may be the way it is supposed to work, but isn't clear.
texdc said on Oct 5, 2007 at 2:32 PM :
It works fine. Just make sure the input text field is set to "Single line", not
"Multiline".
try_test said on Oct 5, 2007 at 9:55 PM :
Check that you have enterd first letter capital.

means, "Frank "will work,but "frank "is wrong.
No screen name said on Oct 12, 2007 at 11:23 AM :
I do not understand the significance of "static". If I were not to add static in this example, what would happen?
No screen name said on Oct 25, 2007 at 5:54 AM :
Hey guys, you must begin programming this code in this way:

mainText.border = true;
textIn.border = true;

var myGreeter:Greeter = new Greeter();
mainText.text = myGreeter.sayHello("");

textIn.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
textIn.addEventListener(KeyboardEvent.KEY_UP, limpaTextField);

function keyPressed(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.ENTER) {
mainText.text = myGreeter.sayHello(textIn.text);
}
}

function limpaTextField(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.ENTER) {
textIn.text = "";
}
}

when we set free the button, the textfield yet guards an 'enter' in him because a 'enter' is composed by the whole process of rise and descent of the button. soon, we should clean this in the rise of the button. did understand me? Sorry for my english =]
skinnycatgide said on Nov 5, 2007 at 8:56 PM :
It's all about setting "textIn" to "single line in" the properties inspector.
kalibahlu said on Nov 27, 2007 at 1:29 PM :
Has anyone been able to get this to work on a Mac? The first example
works fine, but the "enhanced" app doesn't work. Error says "Type was not
found..." and "call to possibly undefined method", and no text appears in
mainText.
York Gibson said on Nov 29, 2007 at 8:14 AM :
Sorry I have diligently followed all of the instructions here and have hit
problems, I've been trying to get started with as3 for days and have got
nowhere. When I run the helloWorld.fla I get:

"Error: Error #2136: The SWF file file:///550Gb%20Bay%202/work/
experimental%2Fuseful/actionscript%203.0%20learning/hello%20world
%20test/HelloWorld.swf contains invalid data.
at Greeter/::frame1()"

Also there is no mention here of how to link to the class file - I have
assumed that I should set the Document Class to Greeter in the
properties inspector??

Can anyone help?
York Gibson said on Dec 4, 2007 at 5:36 AM :
An update to my post above.

I have a secondary internal drive in my MacPro - all of my work is done
on this secondary drive. However all apps etc are installed on the
primary (system drive). The default relative '.' (dot) classpath does not
work in this situation - you have to set the classpath to the location of
your working folder.

All examples/tutorials using the relative classpath work perfectly on the
system drive. They don't if you are working on any other drive.

You won't find this documented ANYWHERE other than here, as far as I
can tell.
No screen name said on Dec 19, 2007 at 8:34 PM :
Sorry, I didn't mean to split this comment.

Anyway, you probably assumed this, but be sure to save both these files in the same folder.
random_ke said on Feb 5, 2008 at 2:33 PM :
when i publish the application, i gave these erors..


1046: type was not found or was not a compile-time constant Greeter
1180: Call to a possibly undefined method Greeter


where is my mistake?
adbe_paul said on Feb 7, 2008 at 10:41 AM :
Those errors mean that Flash isn't able to find the Greeter class definition (the Greeter.as file that you created).

The easiest way to fix this is to make sure that the Greeter.as file is saved in the same folder where your .fla file is saved (you must save the FLA file before testing it in order to use external classes).
ssmithMil said on Feb 26, 2008 at 10:51 AM :
Also, random_ke make sure that your actionscript file is named correctly. I had it as "greeter.as" instead of "Greeter.as" and it wouldn't work.
Paul I said on Feb 27, 2008 at 11:28 AM :
I've been going insane trying to learn AS3 having huge difficulties JUST ATTACHING A CLASSPATH.

Having made the leap of faith that I'm not a complete idiot, I've discovered that if my FLA is in a folder (at any depth / parentage) that has an underscore in the name, then the classpath will simply not connect - or even worse, if the classpath happens to be a correct path in "relative" terms to the FLA, it finds the classes in the relative folder, but fails to import them properly resulting in new even more exciting errors.

The moment I move the FLA and package to folders with underscores - it works. Also, as per a pot above, it will nto work across different drive letters on a PC.

I have wasted hours if not days of my life in these issues, and had all but abandoned plans to learn AS3 as a result.

Have not found this issue mentioned within any documentation, hope this helps somebody else who feels somewhat "up the creek" due to the deficit of classpath info in the documentation.
No screen name said on Apr 17, 2008 at 12:23 AM :
When I executed the code, I wanted to have a way to clear the text box for another user entry. One thing I noticed is that users had to delete previous name entries, or they would continue to add on to the past attempts. I decided to empty the text box every time an entry was made. It works better, but the problem I'm having now is that after the first attempt, I have to press the delete key once or it will not recognize the input names. Any other ways around this?




My code:

mainText.text = myGreeter.sayHello(userNameText.text); userNameText.text = ""; // set input text to empty string
d2burke said on May 9, 2008 at 10:21 PM :
-kalibahlu:

I have a regular macbook and after going through all the steps everything
actually worked just fine. I couldn't think of a reason why its not working for
you, but I figured I'd respond because I hate it when no one responds to my
posts for help :) I'm sure you've figured it out by now anyway.

-Daniel
No screen name said on Jul 26, 2008 at 8:17 PM :
I actually fixed mine because there was a boolean error in the Greeter.as
class. I wrote it so that Greeter.as is in a foler path of
com/example/Greeter.as (in relation the the fla).

package com.example
{
public class Greeter
{
//Define the names that should receieve a greeting.
public static var validNames:Array = ["Dan", "Dave", "Molli"];

//Build a greeting string using the given name.
public function sayHello(userName:String = ""):String
{
var greeting:String;
if (userName == null)
{
greeting = "Hello. Please type your name and press
enter.";
}
else if (validNames.indexOf(userName) > -1)
{
greeting = "Hello " + userName + ".";
}
else {
greeting = "Sorry, you're not on the list";
}
return greeting;
}
}
}

***you can do away with the second function and just add it into the else if
statement in sayHello().

Then everything else is the same in the .fla except you have to import the
class you made at the beginning like this...

import com.example.Greeter;

var myGreeter:Greeter = new Greeter();
mainText.text = myGreeter.sayHello("");

mainText.border = true;
textIn.border = true;

textIn.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);

function keyPressed(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.ENTER)
{
mainText.text = myGreeter.sayHello(textIn.text);
}
}

Then.. everything should work well.
Todays Past said on Aug 1, 2008 at 10:50 AM :
Pet peeve. When teaching a subject to someone the first time, the naming convention you choose can help or hurt. In particular I find that until I'm up to speed, using the same name for more then one item or task can be maddening.

In this example, which almost worked the first time for me (hooray), the choice of using "validName(s)" for both a variable name and a function name just makes it harder to understand the first time around.

Imagine trying to teach someone 2 + 2 = 4, except instead of the operator "+" our language lets us substitute the number "2", and the reader should simply read it as (+) when it appears between two numbers. This gives us the convenience of not needing to print an additional symbol "+".

Now try to teach someone 2 2 2 = 4 instead of 2 + 2 = 4

Good luck

now apply that logic to the code presented and remember you're teaching 2+2 to someone. What exactly is "validName(s)"?

var validNames:Array = ["Sammy", "Frank", "Dean"];
else if (validName(userName))
public static function validName(inputName:String = ""):Boolean
if (validNames.indexOf(inputName) > -1)

is it a function, a variable or is it some language trick that I missed in the readings?


a simple change and confusion is eliminated

var validNames:Array = ["Sammy", "Frank", "Dean"];
else if (checkifvalidName(userName))
public static function checkifvalidName(inputName:String = ""):Boolean
if (validNames.indexOf(inputName) > -1)

Having written code in a bunch of different languages, the first reaction I'd have is "Aw, com'on, if you don't understand the difference between validName and validNames you shouldn't be programming."

Realize that its not about understanding the difference, its about recognizing the difference. While going through the learning process your brain is dealing with information overload (Package, Public, {, instance name, .as, ...). At this time it is easy to confuse validName and validNames, and that can lead to all kinds of frustration.

Long tirade, because as I said its a pet peeve.
graylensman said on Oct 9, 2008 at 6:59 AM :
Actually, this worked like gangbusters for me on my Mac. The few problems I had were due to errors I made inputting the code. Found and fixed those, and it works perfectly.

 

RSS feed | Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/flash/9.0/main/00000035.html