What is Software? | What is Education? | What is Technology? | What is Research? | What is Wi-Fi? | What is Communication? | What is Customer Service?

Free SEO Tutorials & Help

Tutorials:   Adobe Flash   Adobe Photoshop   CorelDRAW   SEO  

Site Map

Website Development | Cable & Broadband Magazine | Solutions for Higher Education | Auction Anything Online

 

Adobe Flash Help & Tutorials

 Back to Topics

 

How to Create an Application with Components (Flash Professional Only)

Creating an Application with Components (Flash Professional Only)

Add the cart

About the Fix Your Mistake tutorial

Display gift details

Build the main page

Add an event listener to trigger the display of gift details

Import the component classes

Add code to the Product Form movie clip

Customize the appearance of components

Create the checkout screen

Display offenses in the combo box

About the Billing, Shipping, and Credit Card panes

Bind data components to display gift ideas

Create the Billing Information pane

Use schema to describe the XML data source

Create the Shipping Information pane

Filter the gift ideas to match the offense

Create the Credit Card Information pane

Add columns to the Gift Ideas section

Add an event listener to the Checkout button

Trigger the XML Connector

Add code for the Checkout screen

Add an event listener to filter the gift ideas

Test the application

Viewing the completed application

Creating an Application with Components (Flash Professional Only)

TOP

Components are prebuilt Flash elements that you can use when creating Macromedia Flash applications. Components include user interface controls, data access and connectivity mechanisms, and media-related elements. Components save you work when building a Flash application by providing you with elements and behavior that you would need to create from scratch otherwise.

This chapter contains a tutorial that shows you how to build a Flash application using components that are available in Macromedia Flash Professional 8. You will learn how to work with components in the Flash authoring environment and also learn how to make them interactive with ActionScript code.
 

About the Fix Your Mistake tutorial

TOP

This tutorial takes you through the steps to create a basic online shopping application for the "Fix Your Mistake" gift service. This service helps a user select an appropriate gift to make amends to someone whom the user has offended. The application filters a list of gifts to those choices that match the severity of the user's offense. From that list the user can add items to the shopping cart and then proceed to the checkout page to provide billing, shipping, and credit card information.

This chapter contains the following sections:

About the Fix Your Mistake tutorial

Build the main page

Bind data components to display gift ideas

Display gift details

Create the checkout screen

Test the application

Viewing the completed application

The application uses the ComboBox, DataGrid, TextArea, and Button components, as well as others, to create the application interface. The main page of the interface looks like this:

The application uses the ActionScript WebService class to connect dynamically to a web service to retrieve the list of offenses (problems.xml) that appear in the combo box. It also uses ActionScript to handle the user's interactions with the application.

The application uses data components to connect the interface to another data source. It uses the XMLConnector component to connect to an XML data file (products.xml) for the list of gifts and it uses the DataSet component to filter the data and present it to the data grid.

The tutorial requires some familiarity with the Flash authoring environment and some experience with ActionScript. In the authoring environment, you should have some experience using panels, tools, the timeline, and the library. All the ActionScript needed for creating the sample application is provided here within the tutorial. To understand the scripting concepts and create your own applications, however, you will need additional experience writing ActionScript.

To see a working version of the completed application, see Viewing the completed application

Keep in mind that the sample application is for demonstration purposes and therefore is not as complete as a real-world application.

Build the main page

TOP

Follow these steps to create the application's main page by adding components to a skeletal starter page. Then add ActionScript code to customize the components, import the ActionScript classes that allow you to manipulate the application's components, and access a web service to populate the combo box with a list of offenses. The code populates the combo box by setting its dataProvider property to receive the results from the web service.

  1. Open the first_app_start.fla file, which you can find at one of the following locations:

    The file contains a start page that looks like the following:

    The start_app.fla file contains three layers: a background layer with a black background image and text titles, a text layer with text labels for sections of the application, and a labels layer with labels on the first frame (Home) and the tenth frame (Checkout).

  2. Select File > Save As. Rename the file and save it to your hard disk.

  3. In the Timeline, select the Labels layer and click the Add Layer button to add a new layer above it. Name the new layer Form. You will place the component instances in this layer.

  4. Make sure the Form layer is selected. In the Components panel (Window > Components), locate the ComboBox component in the User Interface tree. Drag an instance of ComboBox onto the Stage. Place it below the What Did You Do? text. In the Property inspector (Window > Properties > Properties), enter problems_cb for the instance name.

    Enter 400 (pixels) for the width. Enter 76.0 for the x location and 82.0 for the y location.

    NOTE The ComboBox component symbol is added to the library (Window > Library). When you drag an instance of a component to the Stage, the compiled clip symbol for the component is added to the library. As with all symbols in Flash, you can create additional instances of the component by dragging the library symbol onto the Stage.

  5. Drag an instance of the DataGrid component from the User Interface tree in the Components panel onto the Stage. Place it below the Gift Ideas text. Enter products_dg for the instance name. Enter 400 (pixels) for the width and 130 for the height. Enter 76.0 for the x location and 128.0 for the y location.

  6. Drag an instance of the DataSet component from the Data tree in the Components panel onto the side of the Stage. (The DataSet component does not appear in the application at runtime. The DataSet icon is simply a placeholder that you work with in the Flash authoring environment.) Enter products_ds for the instance name.

    Drag an instance of the XMLConnector component from the Data tree in the Components panel to the side of the Stage. (Like the DataSet component, the XMLConnector component does not appear in the application at runtime.) Enter products_xmlcon for the instance name. Click the Parameters tab in the Property inspector, and enter www.flash-mx.com/mm/firstapp/products.xml for the URL property. Click the value for the direction property to activate the combo box, click the down-arrow and select receive from the list.

    NOTE You can also use the Component inspector (Window > Component Inspector) to set parameters for components. The Parameters tab in the Property inspector and the Component inspector work in the same way.

    The URL specifies an external XML file with data about the products that appear in the Gift Ideas section of the application. Later in the tutorial you will use data binding to bind the XMLConnector, DataSet, and DataGrid components together; the DataSet component filters data from the external XML file, and the DataGrid component will display it.

  7. Drag an instance of the Button component from the User Interface tree in the Components panel onto the Stage. Place it in the lower-right corner of the Stage. Enter checkout_button for the instance name. Click the Parameters tab and enter Checkout for the label property. For the x and y coordinates, enter 560.3 and 386.0, respectively.

Import the component classes

TOP

Each component is associated with an ActionScript class file that defines its methods and properties. In this section of the tutorial, you will add ActionScript code to import the classes associated with the application's components. For some of these components, you have already added instances to the Stage. For others, you will add ActionScript later in the tutorial to create instances dynamically.

The import statement creates a reference to the class name and makes it easier to write ActionScript for the component. The import statement enables you to refer to the class by its class name rather than its complete name, which includes the package name. For example, after you create a reference to the ComboBox class file with an import statement, you can refer to instances of the combo box with the syntax instanceName:ComboBox, rather than instanceName:mx.controls.ComboBox.

A package is a directory that contains class files and resides in a designated classpath directory. You can use a wild card character to create references to all the classes in a package: for example, the syntax mx.controls.* creates references to all classes in the controls package. (When you create a reference to a package with a wild card, the unused classes are dropped from the application when it is compiled, so they don't add any extra size.)

For the application in this tutorial, you need the following packages and individual classes:

UI Components Controls package This package contains classes for the user interface control components, including ComboBox, DataGrid, Loader, TextInput, Label, NumericStepper, Button, and CheckBox.

UI Components Containers package This package contains classes for the user interface container components, including Accordion, ScrollPane, and Window. As with the controls package, you can create a reference to this package by using a wild card.

DataGridColumn class This class lets you add columns to the DataGrid instance and control their appearance.

WebService class This class populates the ComboBox instance with a list of problems or offenses. For this class, you will also need to import the WebServiceClasses item from the Classes common library. This item contains compiled clip (SWC) files that you will need in order to compile and generate the SWF file for your application.

Cart class A custom class provided with this tutorial, the Cart class defines the functioning of the shopping cart that you will create later. (To examine the code in the Cart class file, open the cart.as file located in the component_application folder with the application FLA and SWF files).

To import these classes, you will create an Actions layer and add the ActionScript code to the first frame of the main timeline. All the code that you will add to the application in the remaining steps of the tutorial should be placed in the Actions layer.

  1. To import the WebServiceClasses item from the Classes library, select Window > Common Libraries > Classes.

  2. Drag the WebServiceClasses item from the Classes library into the library for the application.

    Importing an item from the Classes library is similar to adding a component to the library: it adds the SWC files for the class to the library. The SWC files need to be in the library in order for you to use the class in an application.

  3. In the Timeline, select the Form layer and click the Add New Layer button. Name the new layer Actions.

  4. With the Actions layer selected, select Frame 1 and press F9 to open the Actions panel.

  5. In the Actions panel, enter the following code to create a stop() function that prevents the application from looping during playback:

    stop();

  6. With Frame 1 in the Actions layer still selected, add the following code in the Actions panel to import the classes:

    // Import necessary classes.

    import mx.services.WebService;

    import mx.controls.*;

    import mx.containers.*;

    import mx.controls.gridclasses.DataGridColumn;

    // Import the custom Cart class.

    import Cart;

Set the data types of component instances

TOP

Next you will assign data types to each of the component instances you dragged to the Stage earlier in the tutorial.

ActionScript 2.0 uses strict data typing, which means that you assign the data type when you create a variable. Strict data typing makes code hints available for the variable in the Actions panel.

  • In the Actions panel, add the following code to assign data types to the four component instances that you already created.

    /* Data type instances on the Stage; other instances might be added at

    runtime from the Cart class.*/

    var problems_cb:ComboBox;

    var products_dg:DataGrid;

    var cart_dg:DataGrid;

    var products_xmlcon:mx.data.components.XMLConnector;

    NOTE The instance names you specify here must agree with the instance names that you assigned when you dragged the components to the Stage.

Customize the appearance of components

TOP

Each component has style properties and methods that let you customize its appearance, including highlight color, font, and font size. You can set styles for individual component instances, or set styles globally to apply to all component instances in an application. For this tutorial you will set styles globally.

  • Add the following code to set styles:

    // Define global styles and easing equations for the problems_cb ComboBox.

    _global.style.setStyle("themeColor", "haloBlue");

    _global.style.setStyle("fontFamily", "Verdana");

    _global.style.setStyle("fontSize", 10);

    _global.style.setStyle("openEasing", mx.transitions.easing.Bounce.easeOut);

    This code sets the theme color (the highlight color on a selected item), font, and font size for the components, and also sets the easing for the ComboBox--the way that the drop-down list appears and disappears when you click the ComboBox title bar.

Display offenses in the combo box

TOP

In this section you will add code to connect to a web service that contains the list of offenses (Forgot to Water Your Plants, and so on). The web service description language (WSDL) file is located at www.flash-mx.com/mm/firstapp/problems.cfc?WSDL. To see how the WSDL is structured, browse to the WSDL location.

The ActionScript code passes the web service results to the ComboBox instance for display. A function sorts the offenses in order of severity. If no result is returned from the web service (for example, if the service is down, or the function isn't found), an error message appears in the Output panel.

  • In the Actions panel, add the following code:

    /* Define the web service used to retrieve an array of problems.

    This service will be bound to the problems_cb ComboBox instance. */

    var problemService:WebService = new WebService("http://www.flash-mx.com/mm/firstapp/problems.cfc?WSDL");

    var myProblems:Object = problemService.getProblems();

    /* If you get a result from the web service, set the field that will be used for the column label.

    Set the data provider to the results returned from the web service. */

    myProblems.onResult = function(wsdlResults:Array) {

    problems_cb.labelField = "name";

    problems_cb.dataProvider = wsdlResults.sortOn("severity", Array.NUMERIC);

    };

    /* If you are unable to connect to the remote web service, display the

    error messages in the Output panel. */

    myProblems.onFault = function(error:Object) {

    trace("error:");

    for (var prop in error) {

    trace(" "+prop+" -> "+error[prop]);

    }

    };

    TIP Press Control+S to save your work and then Control+Enter (or select Control > Test Movie) to test the application. The combo box should be populated with a list of offenses at this point and you should see the empty data grid that you created for Gift Ideas, along with the checkout button.

Bind data components to display gift ideas

TOP

In the beginning of the tutorial, you added instances of the DataGrid, DataSet, and XMLConnector components to the Stage. You set the URL property for the XMLConnector instance, named products_xmlcon, to the location of an XML file containing product information for the Gift Ideas section of the application.

Now you will use data binding features in the Flash authoring environment to bind the XMLConnector, DataSet, and DataGrid components together to use the XML data in the application. For general information on working with data binding and other features of the Flash data integration architecture, see Data Integration (Flash Professional Only) in Using Flash.

When you bind the components, the DataSet component filters the list of products in the XML file according to the severity of the offense that the user selects in the What Did You Do? section. The DataGrid component will display the list.

Use schema to describe the XML data source

TOP

When you connect to an external XML data source with the XMLConnector component, you need to specify a schema--a schematic representation which describes the structure of the XML document. The schema tells the XMLConnector component how to read the XML data source. The easiest way to specify a schema is to import a copy of the XML file that you're going to connect to, and use that copy as a schema.

  1. Open your web browser and go to www.flash-mx.com/mm/firstapp/products.xml (the location you set for the XMLConnector URL parameter).

  2. Select File > Save As.

  3. Save products.xml to the same location as the FLA file that you're working on.

  4. Select Frame 1 in the main Timeline.

  5. Select the products_xmlcon (XMLConnector) instance beside the Stage.

  6. In the Component inspector, click the Schema tab. Click the Import button (on the right side of the Schema tab, above the scroll pane). In the Open dialog box, locate the products.xml file that you imported in step 3, and click Open. The schema for the products.xml file appears in the scroll pane of the Schema tab.

In the top pane of the Schema tab, select the image element. In the bottom pane, select data type and change the value from <empty> to String. Repeat this step for the description element.

Filter the gift ideas to match the offense

TOP

You will use the Binding tab in the Component inspector to bind the XMLConnector, DataSet, and DataGrid component instances to one another.

For information on working with data binding, see Data Integration (Flash Professional Only) in Using Flash.

  1. With the products_xmlcon (XMLConnector) instance selected on the Stage, click the Bindings tab in the Component inspector.

  2. Click the Add Binding button.

  3. In the Add Binding dialog box, select the results.products.product array item and click OK.

  4. In the Bindings tab, click the Bound To item in the Binding Attributes pane (the bottom pane, showing attribute name-value pairs).

  5. In the Value column for the Bound To item, click the magnifying glass icon to open the Bound To dialog box.

  6. In the Bound To dialog box, select the DataSet <products_ds> instance in the Component Path pane. Select dataProvider:array in the Schema Location pane. Click OK.

  7. In the Bindings tab, click the Direction item in the Binding Attributes pane. From the pop-up menu in the Value column, select Out.

    This option means that the data will pass from the products_xmlcon instance to the products_ds instance (rather than passing in both directions, or passing from the DataSet instance to the XMLConnector instance).

  8. On the Stage, select the products_ds instance. In the Bindings tab of the Component inspector, notice that the component's data provider appears in the Binding List (the top pane of the Bindings tab). In the Binding Attributes pane, the Bound To parameter indicates that the products_ds instance is bound to the products_xmlcom instance, and the binding direction is In.

    In the next few steps you will bind the DataSet instance to the DataGrid instance so that the data that is filtered by the data set will be displayed in the data grid.

  9. With the products_ds instance still selected, click the Add Binding button in the Bindings tab.

  10. In the Add Binding dialog box, select the dataProvider: array item and click OK.

  11. In the Bindings tab, make sure the dataProvider: array item is selected in the Binding List.

  12. Click the Bound To item in the Binding Attributes pane.

  13. In the Value column for the Bound To item, click the magnifying glass icon to open the Bound To dialog box.

  14. In the Bound To dialog box, select the products_dg (DataGrid) instance in the Component Path pane. Select dataProvider:array in the Schema Location pane. Click OK.

Add columns to the Gift Ideas section

TOP

Now you are ready to add columns to the data grid in the Gift Ideas section of the application, for displaying product information and price.

  • Select the Actions layer. In the Actions panel, add the following code to create, configure, and add a Name column and a Price column to the DataGrid instance:

    // Define data grid columns and their default widths in the products_dg

    // DataGrid instance.

    var name_dgc:DataGridColumn = new DataGridColumn("name");

    name_dgc.headerText = "Name";

    name_dgc.width = 280;

    // Add the column to the DataGrid.

    products_dg.addColumn(name_dgc);

    var price_dgc:DataGridColumn = new DataGridColumn("price");

    price_dgc.headerText = "Price";

    price_dgc.width = 100;

    // Define the function that will be used to set the column's label

    // at runtime.

    price_dgc.labelFunction = function(item:Object) {

    if (item != undefined) {

    return "$"+item.price+" "+item.priceQualifier;

    }

    };

    products_dg.addColumn(price_dgc);

Trigger the XML Connector

TOP

Next you will add a line of code that causes the XMLConnector instance to load, parse, and bind the contents of the remote products.xml file. This file is located at the URL you entered for the URL property of the XMLConnector instance that you created earlier. The file contains information on the products that will appear in the Gift Ideas section of the application.

  • Add the following code in the Actions panel:

    products_xmlcon.trigger();

Add an event listener to filter the gift ideas

TOP

In this section, you add an event listener to detect when a user selects an offense in the What Did You Do? section (the problems_cb ComboBox instance). The listener includes a function that filters the Gift Ideas list according to the offense the user chooses. Selecting a minor offense displays a list of modest gifts (such as a CD or flowers); selecting a more serious offense displays more opulent gifts.

For more information on working with event listeners, see Using event listeners in Learning ActionScript 2.0 in Flash.

  • In the Actions panel, add the following code:

    /* Define a listener for the problems_cb ComboBox instance.

    This listener will filter the products in the DataSet (and DataGrid).

    Filtering is based on the severity of the currently selected item in the ComboBox. */

    var cbListener:Object = new Object();

    cbListener.change = function(evt:Object) {

    products_ds.filtered = false;

    products_ds.filtered = true;

    products_ds.filterFunc = function(item:Object) {

    // If the current item's severity is greater than or equal to the

    // selected item in the ComboBox, return true.

    return (item.severity>=evt.target.selectedItem.severity);

    };

    };

    // Add the listener to the ComboBox.

    problems_cb.addEventListener("change", cbListener);

Resetting the filtered property (setting it to false and then to true) at the beginning of the change() function ensures that the function will work properly if the user changes the What Did YouDo? selection repeatedly.

The filterFunc() function checks whether a given item in the array of gifts falls within the severity the user selected in the combo box. If the gift is within the selected severity range, it is displayed in the DataGrid instance (which is bound to the DataSet instance).

The last line of code registers the listener to the problems_cb ComboBox instance.

Add the cart

TOP

The next code that you will add creates an instance of the custom Cart class and initializes it.

In the Actions panel, add the following code:

var myCart:Cart = new Cart(this);

myCart.init();

This code uses the init() method of the Cart class to add a DataGrid instance to the Stage, define the columns, and position the DataGrid instance on the Stage. It also adds a Button component instance and positions it, and adds an Alert handler for the button. (To see the code for the Cart class init() method, open the Cart.as file.)

TIP Press Control+S to save your work and then Control+Enter (or select Control->Test Movie) to test the application. When you select an offense in the combo box, the data grid that you created for Gift Ideas should display a subset of gifts to match the selected offense.

Display gift details

TOP

A pop-up window appears in the application when a user clicks a product in the Gift Ideas section. The pop-up window contains component instances that display information about the product, including a text description, an image, and the price. To make this pop-up window, you will create a movie clip symbol and add instances of the Loader, TextArea, Label, NumericStepper, and Button components. The product detail window for Bouquet of Flowers Extreme looks like this:



You will later add ActionScript that dynamically creates an instance of this movie clip for each product. These movie clip instances will be displayed in the Window component, which you added to the library earlier. The component instances will be populated with elements from the external XML file.

  1. Drag an instance of the Window component from the User Interface tree in the Components panel to the library.

    The Window component symbol is now added to the library. Later in the tutorial, you will create instances of the Window component using ActionScript.

  2. In the Library panel (Window > Library), click the options menu on the right side of the title bar and select New Symbol.

  3. In the Create New Symbol dialog box, enter ProductForm for Name and select Movie Clip for Type.

  4. Click the Advanced button. Under Linkage, select Export for ActionScript, leave Export in First Frame selected, and click OK. A document window for the new symbol opens in symbol-editing mode.

    For movie clip symbols that are in the library but not on the Stage, you must select Export for ActionScript so that you can manipulate them using ActionScript. (Exporting in first frame means that the movie clip is available as soon as the first frame loads.) Later in the tutorial you will add ActionScript that will generate an instance of the movie clip dynamically each time a user clicks a product in the Gift Ideas section.

  5. In the Timeline for the new symbol, select Layer 1 and rename it Components.

  6. Drag an instance of the Loader component from the User Interface tree in the Components panel onto the Stage. Enter 5, 5 for the x, y coordinates respectively. Enter image_ldr for the instance name. Click the Parameters tab in the Property inspector. Select false for autoLoad and false for scaleContent.

    The Loader component instance will be used to display an image of the product. The false setting for autoLoad specifies that the image will not load automatically. The false setting for scaleContent specifies that the image will not be scaled. Later in the tutorial you will add code that loads the image dynamically, based on the product that the user selects in the Gift Ideas section.

  7. Drag an instance of the TextArea component from the User Interface tree in the Components panel onto the Stage. Place it next to the Loader component. Enter 125, 5 for the x, y coordinates respectively. Enter description_ta for the instance name. Set the Width to 200 and Height to 130. Click the Parameters tab in the Property inspector. For editable, select false. For html, select true. For wordWrap, select true.

    The TextArea component instance is used to display a text description of the selected product. The selected settings specify that the text cannot be edited by a user, that it can be formatted with HMTL tags, and that lines will wrap to fit the size of the text area.

  8. Drag an instance of the Label component from the User Interface tree in the Components panel onto the Stage. Place it below the Loader component. Set the x, y coordinates to 5, 145. Enter price_lbl for the instance name. Click the Parameters tab in the Property inspector. For autoSize, select left. For html, select true.

    The Label component instance will display the price of the product and the price qualifier (the quantity of products indicated by the specified price, such as "each" or "one dozen.")

  9. Drag an instance of the NumericStepper component from the User Interface tree in the Components panel onto the Stage. Place it below the TextArea component. Set the x, y coordinates to 135, 145. Enter quantity_ns for the instance name. Click the Parameters tab in the Property inspector. For minimum, enter 1.

    Setting minimum to 1 specifies that the user must select at least one of the products in order to add the item to the cart.

  10. Drag an instance of the Button component from the User Interface tree in the Components panel onto the Stage. Place it beside the NumericStepper component. Set the x, y coordinates to 225, 145. Enter addToCart_button for the instance name. Click the Parameters tab in the Property inspector. For label, enter Add To Cart.

Add an event listener to trigger the display of gift details

TOP

Next you will add an event listener to the products_dg DataGrid instance to display information about each product. When the user clicks a product in the Gift Ideas section, a pop-up window appears with information about the product.

  • In the Actions panel of the main Timeline, add the following code:

    // Create a listener for the DataGrid to detect when the row in the

    // DataGrid is changed

    var dgListener:Object = new Object();

    dgListener.change = function(evt:Object) {

    // When the current row changes in the DataGrid, launch a new pop-up

    // window displaying the product's details.

    myWindow = mx.managers.PopUpManager.createPopUp(_root, mx.containers.Window, true, {title:evt.target.selectedItem.name, contentPath:"ProductForm", closeButton:true});

    // Set the dimensions of the pop-up window.

    myWindow.setSize(340, 210);

    // Define a listener that closes the pop-up window when the user clicks

    // the close button.

    var closeListener:Object = new Object();

    closeListener.click = function(evt) {

    evt.target.deletePopUp();

    };

    myWindow.addEventListener("click", closeListener);

    };

    products_dg.addEventListener("change", dgListener);

This code creates a new event listener called dgListener, and creates instances of the Window component you added to the library earlier. The title for the new window is set to the product's name. The content path for the window is set to the ProductForm movie clip. The size of the window is set to 340 x 210 pixels.

The code also adds a close button to enable the user to close the window after viewing the information.

Add code to the Product Form movie clip

TOP

Next, you will add ActionScript to the ProductForm movie clip that you just created. The ActionScript populates the components in the movie clip with information about the selected gift, and adds an event listener to the Add to Cart button that adds the selected product to the cart.

For more information on working with event listeners, see Using event listeners in Using ActionScript in Flash.

  1. In the Timeline of the ProductForm movie clip, create a new layer and name it Actions. Select the first frame in the Actions layer.

  2. In the Actions panel, add the following code:

    // Create an object to reference the selected product item in the DataGrid.

    var thisProduct:Object = this._parent._parent.products_dg.selectedItem;

    // Populate the description_ta TextArea and price_lbl Label instances with

    // data from the selected product.

    description_ta.text = thisProduct.description;

    price_lbl.text = "<b>$"+thisProduct.price+" "+thisProduct.priceQualifier+"</b>";

    // Load an image of the product from the application directory.

    image_ldr.load(thisProduct.image);

    NOTE The code includes comments explaining its purpose. It's a good idea to include comments like these in all the ActionScript code you write, so that you or anyone else going back to the code later can easily understand what it was for.

    First, the code defines a variable to refer to the selected product in the subsequent code. Using the thisProduct variable means you don't have to refer to the specified product using the path this._parent._parent.products_dg.selectedItem.

    Next, the code populates the TextArea and Label instances by using the description, price, and priceQualifier properties of the thisProduct object. These properties correspond to elements in the products.xml file that you linked to the products_xmlcon XMLConnector instance at the beginning of the tutorial. Later in the tutorial, you will bind the XMLConnector, DataSet, and DataGrid component instances together, and the elements in the XML file will populate the other two component instances.

    Finally, the code uses the image property of the thisProduct object instance to load an image of the product into the Loader component.

  3. Next you will add an event listener to add the product to the cart when the user clicks the Add to Cart button. (You will add ActionScript to the main Timeline in the application later in the tutorial, to create an instance of the Cart class.) Add the following code:

    var cartListener:Object = new Object();

    cartListener.click = function(evt:Object) {

    var tempObj:Object = new Object();

    tempObj.quantity = evt.target._parent.quantity_ns.value;

    tempObj.id = thisProduct.id;

    tempObj.productObj = thisProduct;

    var theCart = evt.target._parent._parent._parent.myCart;

    theCart.addProduct(tempObj.quantity, thisProduct);

    };

    addToCart_button.addEventListener("click", cartListener);

  4. Click the Check Syntax button (the blue check mark above the Script pane) to make sure there are no syntax errors in the code.

    You should check syntax frequently as you add code to an application. Any errors found in the code are listed in the Output panel. (When you check syntax, only the current script is checked; other scripts that may be in the FLA file are not checked.) For more information, see Debugging your scripts in Learning ActionScript 2.0 in Flash.

  5. Click the arrow button at the upper left of the Document window or select View > Edit Document to exit symbol editing mode and return to the main Timeline.

TIP Press Control+S to save your work and then Control+Enter (or select Control >Test Movie) to test your application. When you click a gift selection now, a window should appear and display an image of the gift, accompanied by a description, the price, and a numeric stepper that allows you to choose the quantity that you want.

Create the checkout screen

TOP

When the user clicks the Checkout button on the main screen, the Checkout screen appears. The Checkout screen provides forms where the user can enter billing, shipping, and credit card information. The checkout screen looks like the following:

The checkout interface consists of components placed on a keyframe at Frame 10 in the application. You will use the Accordion component to create the checkout interface. The Accordion component is a navigator that contains a sequence of children that it displays one at a time. You will also add a Button component instance to create a Back button, so users can return to the main screen.

Later in the tutorial, you will create movie clips to use as children in the Accordion instance, to display the Billing, Shipping, and Credit Card Information panes.

  1. In the main Timeline for the application, move the playhead to Frame 10 (labeled Checkout). Make sure the Form layer is selected.

  2. Insert a blank keyframe on Frame 10 in the Form layer (select the frame and select Insert > Timeline > Blank Keyframe).

  3. With the new keyframe selected, drag an instance of the Accordion component from the User Interface tree in the Components panel onto the Stage. In the Property inspector, enter

  4. checkout_acc for the instance name. Set the width to 300 pixels and the height to 200 pixels.

    Drag an instance of the Button component from the User Interface tree in the Components panel onto the lower-right corner of the Stage. In the Property inspector, enter back_button for the instance name. Click the Parameters tab, and enter Back for the label property.

About the Billing, Shipping, and Credit Card panes

TOP

The Billing, Shipping, and Credit Card Information panes are built with movie clip instances that are displayed in the Accordion component instance. Each pane consists of two nested movie clips.

The parent movie clip contains a ScrollPane component, used to display content in a scrollable area. The child movie clip contains Label and TextInput components where users can enter personal data, such as name, address, and so on. You will use the ScrollPane component to display the child movie clip so that the user can scroll through the information fields.

Create the Billing Information pane

TOP

First you will create two movie clips that will display the Billing Information form fields: a parent movie clip with the ScrollPane component instance, and a child movie clip with the Label and TextArea component instances.

  1. In the Library panel (Window > Library), click the options menu on the right side of the title bar and select New Symbol.

  2. In the Create New Symbol dialog box, enter checkout1_mc for Name and select Movie Clip for Type.

  3. Click the Advanced button. Under Linkage, select Export for ActionScript, leave Export in First Frame selected, and click OK.

    A document window for the new symbol opens in symbol-editing mode.

  4. Drag an instance of the ScrollPane component onto the Stage.

  5. In the Property inspector, enter checkout1_sp for the instance name. Set the W and H values to 300, 135. Set the x and y coordinates to 0, 0.

  6. Click the Parameters tab. Set the contentPath property to checkout1_sub_mc.

    The checkout1_sub_mc movie clip appears inside the scroll pane, and contains the Label and TextInput components. You will create this movie clip next.

  7. From the Library options menu, select New Symbol.

  8. In the Create New Symbol dialog box, enter checkout1_sub_mc for Name and select Movie Clip for Type.

  9. Click the Advanced button. Under Linkage, select Export for ActionScript, leave Export in First Frame selected, and click OK.

    A document window for the new symbol opens in symbol-editing mode.

  10. Drag six instances of the Label component onto the Stage. Alternatively, you can drag one instance onto the Stage, and Control-click (Windows) or Option-click (Macintosh) to drag it on the Stage to make copies. Name and position the instances as follows:

    • For the first instance, enter firstname_lbl for the instance name and set the x and y coordinates to 5, 5. Click the Parameters tab and enter First Name for text.

    • For the second instance, enter lastname_lbl for the instance name and set the x and y coordinates to 5, 35. Click the Parameters tab and enter Last Name for text.

    • For the third instance, enter country_lbl for the instance name and set the x and y coordinates to 5, 65. Click the Parameters tab and enter Country for text.

    • For the fourth instance, enter province_lbl for the instance name and set the x and y coordinates to 5, 95. Click the Parameters tab and enter Province/State for text.

    • For the fifth instance, enter city_lbl for the instance name and set the x and y coordinates to 5, 125. Click the Parameters tab and enter City for text.

    • For the sixth instance, enter postal_lbl for the instance name and set the x and y coordinates to 5, 155. Click the Parameters tab and enter Postal/Zip Code for text.

  11. Drag six instances of the TextInput component onto the Stage. Place a TextInput instance immediately to the right of each Label instance. For example, the x, y coordinates of the first

    TextInput instance should be 105, 5. Name the TextInput instances as follows:

    • Name the first instance billingFirstName_ti.

    • Name the second instance billingLastName_ti.

    • Name the third instance billingCountry_ti.

    • Name the fourth instance billingProvince_ti.

    • Name the fifth instance billingCity_ti.

    • Name the sixth instance billingPostal_ti.

    Sometimes content in a scroll pane can be cropped if it's too close to the border of the pane. In the next few steps you will add a white rectangle to the checkout1_sub_mc movie clip so that the Label and TextInput instances are displayed properly.

  12. In the Timeline, click the Add New Layer button. Drag the new layer below the existing layer. (The layer with the rectangle should be on the bottom, so that the rectangle doesn't interfere with the component display.)

  13. Select Frame 1 of the new layer.

  14. In the Tools panel, select the Rectangle tool. Set the Stroke color to None and the Fill color to white.

    Click the Stroke Color control in the Tools panel and click the None button--the white swatch with a red line through it. Click the Fill Color control and click the white color swatch.

  15. Drag to create a rectangle that extends beyond the bottom and right edges of the Label and TextInput instances.

Create the Shipping Information pane

TOP

The movie clips for the Shipping Information pane are similar to those for the Billing Information pane. You will also add a CheckBox component, enabling users to populate the Shipping Information form fields with the same data they entered in the Billing Information pane.

  1. Follow the earlier instructions (see Create the Billing Information pane) to create the movie clips for the Credit Card Information pane. Note these naming differences:

    • For the first movie clip, enter checkout2_mc for the symbol name and checkout2_sp for the instance name. In the Property inspector's Parameters tab, set the contentPath property to checkout2_sub_mc.

    • For the second movie clip, enter checkout2_sub_mc for the symbol name.

    • For the TextInput instances, change "billing" to "shipping" in the instance names.

  2. With the checkout2_sub_mc movie clip open in symbol-editing mode, drag an instance of the CheckBox component onto the Stage and position it just above the first Label instance.

    Make sure to place this instance in Layer 1, along with the other component instances.

  3. In the Property inspector, enter sameAsBilling_ch for the instance name.

  4. Click the Parameters tab. Set the label property to Same As Billing Info.

Create the Credit Card Information pane

TOP

The movie clips for the Credit Card Information pane are also similar to those for the Billing and Shipping Information panes. However, the nested movie clip for the Credit Card Information pane has somewhat different fields than the other two panes, for credit card number and other card data.

  1. Follow steps 1-9 of the Billing Information instructions (see Create the Billing Information pane) to create the movie clips for the Credit Card Information pane. Note these naming differences:

    • For the first movie clip, enter checkout3_mc for the symbol name and checkout3_sp for the instance name. In the Property inspector's Parameters tab, set the contentPath property to checkout3_sub_mc.

    • For the second movie clip, enter checkout3_sub_mc for the symbol name.

  2. Drag four instances of the Label component onto the Stage. Name and position the instances as follows:

    • For the first instance, enter ccName_lbl for the instance name and set the x and y coordinates to 5, 5. Click the Parameters tab and enter Name On Card for text.

    • For the second instance, enter ccType_lbl for the instance name and set the x and y coordinates to 5, 35. Click the Parameters tab and enter Card Type for text.

    • For the third instance, enter ccNumber_lbl for the instance name and set the x and y coordinates to 5, 65. Click the Parameters tab and enter Card Number for text.

    • For the fourth instance, enter ccExp_lbl for the instance name and set the x and y coordinates to 5, 95. Click the Parameters tab and enter Expiration for text.

  3. Drag an instance of the TextInput component onto the Stage and position it to the right of the ccName_lbl instance. Name the new instance ccName_ti. Set the x and y coordinates to 105, 5. Set the width to 140.

  4. Drag an instance of the ComboBox component onto the Stage and position it to the right of the ccType_lbl instance. Name the new instance ccType_cb. Set the x and y coordinates to 105, 35. Set the width to 140.

  5. Drag another instance of the TextInput component onto the Stage and position it to the right of the ccNumber_lbl instance. Name the new instance ccNumber_ti. Set the x and y coordinates to 105, 65. Set Width to 140.

  6. Drag two instances of the ComboBox component onto the Stage. Position one to the right of the ccExp_lbl instance, and position the other one to the right of that. Name the first new instance ccMonth_cb. Set Width to 60 and the x and y coordinates to 105, 95. Name the second ccYear_cb. Set Width to 70 and the x and y coordinates to 175, 95.

  7. Drag an instance of the Button component onto the Stage and position it at the bottom of the form, below the ccMonth_cb instance. Name the new instance checkout_button. Set the x and y coordinates to 125, 135. In the Property inspector's Parameters tab, set the label property to Checkout.

  8. Follow the instructions in steps 14-15 of the Billing Information instructions (see Create the Billing Information pane) to add a rectangle to the bottom of the form.

Add an event listener to the Checkout button

TOP

Now you will add code to display the Checkout screen when the user clicks the Checkout button.

In the Actions panel for the main page, add the following code:

// When the Checkout button is clicked, go to the "checkout" frame label.

var checkoutBtnListener:Object = new Object();

checkoutBtnListener.click = function(evt:Object) {

evt.target._parent.gotoAndStop("checkout");

};

checkout_button.addEventListener("click", checkoutBtnListener);

This code specifies that, when the user clicks the Checkout button, the playhead moves to the Checkout label in the Timeline.

Add code for the Checkout screen

TOP

Now you're ready to add code to the Checkout screen of the application, on Frame 10 in the main Timeline. This code processes the data that users enter in the Billing, Shipping, and Credit Card Information panes that you created earlier with the Accordion component and other components.

  1. In the Timeline, select Frame 10 in the Actions layer and insert a blank keyframe (select Insert > Timeline > Blank Keyframe)

  2. Open the Actions panel (F9).

  3. In the Actions panel, add the following code:

    stop();

    import mx.containers.*;

    // Define the Accordion component on the Stage.

    var checkout_acc:Accordion;

  4. Next you will add the first child to the Accordion component instance, to accept billing information from the user. Add the following code:

    // Define the children for the Accordion component.

    var child1 = checkout_acc.createChild("checkout1_mc", "child1_mc", {label:"1. Billing Information"});

    var thisChild1 = child1.checkout1_sp.spContentHolder;

    The first line calls the createChild() method of the Accordion component and creates an instance of the checkout1_mc movie clip symbol (which you created earlier) with the instance name child1_mc and the label "1. Billing Information". The second line of code creates a shortcut to an embedded ScrollPane component instance.

  5. Create the second child for the Accordion instance, to accept shipping information:

    /* Add the second child to the Accordion.

    Add an event listener for the sameAsBilling_ch CheckBox.

    This copies the form values from the first child into the second child. */

    var child2 = checkout_acc.createChild("checkout2_mc", "child2_mc", {label:"2. Shipping Information"});

    var thisChild2 = child2.checkout2_sp.spContentHolder;

    var checkboxListener:Object = new Object();

    checkboxListener.click = function(evt:Object) {

    if (evt.target.selected) {

    thisChild2.shippingFirstName_ti.text = thisChild1.billingFirstName_ti.text;

    thisChild2.shippingLastName_ti.text = thisChild1.billingLastName_ti.text;

    thisChild2.shippingCountry_ti.text = thisChild1.billingCountry_ti.text;

    thisChild2.shippingProvince_ti.text = thisChild1.billingProvince_ti.text;

    thisChild2.shippingCity_ti.text = thisChild1.billingCity_ti.text;

    thisChild2.shippingPostal_ti.text = thisChild1.billingPostal_ti.text;

    }

    };

    thisChild2.sameAsBilling_ch.addEventListener("click", checkboxListener);

    The first two lines of code are similar to the code for creating the Billing Information child: you create an instance of the checkout2_mc movie clip symbol, with the instance name child2_mc and the label "2. Shipping Information". The second line of code creates a shortcut to an embedded ScrollPane component instance.

    Beginning with the third line of code, you add an event listener to the CheckBox instance. If the user clicks the check box, the shipping information uses the data the user entered in the

    Billing Information pane.

  6. Next, create a third child for the Accordion instance, for credit card information:

    // Define the third Accordion child.

    var child3 = checkout_acc.createChild("checkout3_mc", "child3_mc", {label:"3. Credit Card Information"});

    var thisChild3 = child3.checkout3_sp.spContentHolder;

  7. Add this code to create ComboBox instances for the credit card month, year, and type, and populate each with a statically defined array:

    /* Set the values in the three ComboBox instances on the Stage:

    ccMonth_cb, ccYear_cb and ccType_cb */

    thisChild3.ccMonth_cb.labels = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];

    thisChild3.ccYear_cb.labels = [2004, 2005, 2006, 2007, 2008, 2009, 2010];

    thisChild3.ccType_cb.labels = ["VISA", "MasterCard", "American Express", "Diners Club"];

  8. Finally, add the following code to add event listeners to the Checkout button and the Back button. When the user clicks the Checkout button, the listener object copies the form fields from the

    Billing, Shipping, and Credit Card Information panes into a LoadVars object that is sent to the server. (The LoadVars class lets you send all the variables in an object to a specified URL.)

    When the user clicks the Back button, the application returns to the main screen.

    /* Create a listener for the checkout_button Button instance.

    This listener sends all the form variables to the server when the user clicks the Checkout button. */

    var checkoutListener:Object = new Object();

    checkoutListener.click = function(evt:Object){

    evt.target.enabled = false;

    /* Create two LoadVars object instances, which send variables to

    and receive results from the remote server. */

    var response_lv:LoadVars = new LoadVars();

    var checkout_lv:LoadVars = new LoadVars();

    checkout_lv.billingFirstName = thisChild1.billingFirstName_ti.text;

    checkout_lv.billingLastName = thisChild1.billingLastName_ti.text;

    checkout_lv.billingCountry = thisChild1.billingCountry_ti.text;

    checkout_lv.billingProvince = thisChild1.billingProvince_ti.text;

    checkout_lv.billingCity = thisChild1.billingCity_ti.text;

    checkout_lv.billingPostal = thisChild1.billingPostal_ti.text;

    checkout_lv.shippingFirstName = thisChild2.shippingFirstName_ti.text;

    checkout_lv.shippingLastName = thisChild2.shippingLastName_ti.text;

    checkout_lv.shippingCountry = thisChild2.shippingCountry_ti.text;

    checkout_lv.shippingProvince = thisChild2.shippingProvince_ti.text;

    checkout_lv.shippingCity = thisChild2.shippingCity_ti.text;

    checkout_lv.shippingPostal = thisChild2.shippingPostal_ti.text;

    checkout_lv.ccName = thisChild3.ccName_ti.text;

    checkout_lv.ccType = thisChild3.ccType_cb.selectedItem;

    checkout_lv.ccNumber = thisChild3.ccNumber_ti.text;

    checkout_lv.ccMonth = thisChild3.ccMonth_cb.selectedItem;

    checkout_lv.ccYear = thisChild3.ccYear_cb.selectedItem;

    /* Send the variables from the checkout_lv LoadVars to the remote script on the server.

    Save the results in the response_lv instance. */

    checkout_lv.sendAndLoad("http://www.flash-mx.com/mm/firstapp/cart.cfm", response_lv, "POST");

    response_lv.onLoad = function(success:Boolean) {

    evt.target.enabled = true;

    };

    };

    thisChild3.checkout_button.addEventListener("click", checkoutListener);

    cart_mc._visible = false;

    var backListener:Object = new Object();

    backListener.click = function(evt:Object) {

    evt.target._parent.gotoAndStop("home");

    }

back_button.addEventListener("click", backListener);

Test the application

TOP

Congratulations! You've finished building the application. Now press Control+S to save your work and then Control+Enter (or select Control >Test Movie) to test the application.

Viewing the completed application

TOP

In the event that you have not been able to successfully complete the tutorial, you can view a working version of the completed application. You can find this starter Flash (FLA) file,

first_app_start.fla, and the finished file, first_app.fla, in the Samples folder on your hard disk:

To view the FLA file for the application, open the first_app.fla file in the components_application folder.

You can compare these files to your own to help you find your errors.

All the components used in the application appear in the library (along with graphics files and other assets used to create the application). Some components appear as instances on the Stage. Some are referenced in the ActionScript code and do not appear until runtime.

Copyright ADOBE - All Rights Reserved Worldwide

 

 

More Topics:

Working with Flash Documents

How to work in Flash WorkSpace

Working with Projects in Flash

Process to Build your First Application in Flash

Using Symbols, Instances and Library Assets in Flash

How to Build Video Player in Flash

How to Work with Color, Strokes and Fills in Flash

How to Create Document in Flash

What is Vector and Bitmap Graphics in Flash

How to Create a Banner in Flash, Part 1

How to Work with Text in Flash

How to Create a Banner in Flash, Part 2

How to Use Imported Artwork in Flash

How to Create a Banner in Flash, Part 3

How to Work with Graphic Objects in Flash

How to Work with Layers in Flash

How to Use Filters and Blends

Working with Graphics in Flash

What is Accessibility Features in Flash

How to Create Motion (Shape Tween & Motion Tween) in Flash

How to Create an Application in Flash

What is Masking in Flash

How to Work with Video in Flash

How to Use Layout Tools in Flash

What are Behaviors in Flash

How to Work with Sound in Flash

How to Create Symbols and Instances in Flash

What is ActionScript in Flash

How to Write ActionScript With Script Assist in Flash

How to Add Button Animation and Navigation in Flash

What is Data Integration in Flash

How to Work with Screens

How to Create a Presentation with Screens

What is Extending Flash

How to Create Multilanguage Text in Flash

How to Create Graphics: Draw in Flash

What is Flash Lite

Ways of Data Integration

How to Create Graphics: Create a Timeline Animation in Flash

Getting Started with Flash Lite in Flash

How to Publish Flash Documents

How to Create Graphics: Making Animations with Easing

Learning Flash Lite 1.X ActionScript in Flash

How to Export Flash Content and Images from Flash

How to Create Graphics: Applying Gradients in Flash

Process of Writing and Editing ActionScript 2.0 in Flash

How to Create Accessible Content in Flash

How to Create Graphics: Apply Graphic Filters and Blends

What is Data and Data Types in Flash

Process of Printing from SWF Files in Flash

Using ActionScript: How to Use Script Assist mode in Flash

Learn Syntax and Language Fundamentals in Flash

How to Create E-learning Content in Flash

Using ActionScript: How to Write Scripts in Flash

Working with Functions and Methods in Flash

Process of Using Templates in Flash

Using ActionScript: Process of Adding Interactivity in Flash

What are Classes in Flash

Control Tag Summary of XML to UI in Flash

Using ActionScript: How to Create a Form with Conditional Logic and Send Data in Flash

What is Inheritance in Flash

What is Data Integration: Overview

Using ActionScript: How to Work with Objects and Classes in Flash

Overview on Interfaces in Flash

What is Data Integration: Using XML for a Timesheet

How to Work with Text and Strings in Flash

How to use Handling Events in Flash

What is Data Integration: Using XUpdate to Update the Timesheet

Learning Animation, Filters and Drawings in Flash

How to Work with Movie Clips in Flash

How to Create Interaction with ActionScript in Flash

How to Work with Images, Sound, and Video in Flash

How to Work with External Data in Flash

What is Security in Flash

How to Debug Applications in Flash

List of Error Messages in Flash

Using Object-Oriented Programming with ActionScript 1.0 in Flash

How to Write Scripts for Earlier Versions of Flash Player in Flash

List of all Keyboard Keys and Key Code Values for using in Flash

Terminology

Introduction to Components in Flash

What are Components in Flash

How to Create an Application with Components

How to Work with Components in Flash

How to Handle Component Events in Flash

How to Customize Components in Flash

How to Create Components in Flash

What is Collection Properties in Flash