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" to the user name that is given.

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

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

Creating an application that uses your ActionScript code

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

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

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, type mainText as the instance name of the text field.
  6. Click the first frame of the main timeline.
  7. In the Actions panel, type the following script:
    var myGreeter:Greeter = new Greeter();
    mainText.text = myGreeter.sayHello("Bob");
    
  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. The "Hello, Bob" text is displayed.

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

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. Type textIn as the instance name.
  6. Click the first frame of the main timeline.
  7. In the Actions panel, add the following lines to the end of the existing script:
    mainText.border = true;
    textIn.border = true;
    
    textIn.addEventListener(KeyboardEvent.KEY_UP, keyPressed);
    
    function keyPressed(event:Event):void
    {
        if (event.keyCode == Keyboard.ENTER)
        {
            mainText.text = myGreeter.sayHello(textIn.text);
        }
    }
    

    The new code adds the following functionality:

    • The first two lines simply define borders for two text fields.
    • 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.
    • 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:

    mainText.border = true;
    textIn.border = true;
    
    var myGreeter:Greeter = new Greeter();
    mainText.text = myGreeter.sayHello("");
    
    textIn.addEventListener(KeyboardEvent.KEY_UP, keyPressed);
    
    function keyPressed(event:Event):void
    {
        if (event.keyCode == Keyboard.ENTER)
        {
            mainText.text = myGreeter.sayHello(textIn.text);
        }
    }
    
  8. Save the file.
  9. 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.