Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Design > Adobe Creative Suite

  • Print
  • + Share This
This chapter is from the book

Creating Buttons Dynamically

If you want to create a button dynamically—that is, during runtime while your Flash movie is playing—you can do so with the constructor new SimpleButton(). Creating buttons on the fly allows you to respond to your user and a changing environment and not rely on buttons that have been created in advance. After creating a new button from the SimpleButton class, you define its four keyframes, the Up, Over, Down, and Hit states, by assigning other objects to the properties upState, overState, downState, and hitTestState.

The upState, overState, downState, and hitTestState properties can take any kind of display object such as a loaded JPEG image, a movie clip, text field, or a dynamically drawn shape or sprite. In Chapter 7, “Controlling and Displaying Graphics,” you’ll learn to create and manage the graphics on the Stage. In this example task, you’ll create four shapes dynamically with the new Shape() constructor, and then assign those shapes to the keyframes of a newly created button.

To create a button dynamically

  1. Select the first frame of the Timeline, and open the Actions panel.
  2. In the Script pane, enter the following code that creates a new Shape object and then draws a filled circle:
    var myup:Shape = new Shape();;

    The new Shape object called myup is created. The beginFill() method defines the color of the fill, and the drawCircle() method defines its location and size.

  3. Create three more new shapes with different colors in the same manner circle-a.jpg.

    These four shapes will be assigned to the four keyframes of the new button.

  4. In the next line, instantiate a new button from the SimpleButton class, like so:
    var mybutton:SimpleButton = new SimpleButton();
  5. Next, assign the four shapes to the properties of your new button as in the following code:
    mybutton.upState = myup;
    mybutton.overState = myover;
    mybutton.downState = mydown;
    mybutton.hitTestState = myhit;
  6. To see the new button on the Stage, you must add it to the Stage to be displayed with the following code:

    To see any dynamically generated graphic, you always need to use the method addChild(). The full Action-Script code can be seen in circle-b.jpg.

  7. Test your movie by choosing Control > Test Movie > in Flash Professional circle-c.jpg.
  • + Share This
  • 🔖 Save To Your Account