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. Rather than rely on buttons that have been created in advance, you can capture graphics that a user might draw or upload, and use them as buttons. 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, 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();;,100,10);
    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 (Figure 4.49).
    Figure 4.49

    Figure 4.49 Four circles are created dynamically (lines 1–15). Each circle is an object of the Shape class.

    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:
  6. Finally, in order 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 ActionScript code can be seen in Figure 4.50.
    Figure 4.50

    Figure 4.50 A button is created dynamically (line 17) and the four shapes are assigned to the button's upState, overState, downState, and hitTestState (lines 19–22).

  7. Test your movie by choosing Control > Test Movie (Figure 4.51).
    Figure 4.51

    Figure 4.51 The circle shape appears on the Stage and behaves like a button.

  • + Share This
  • 🔖 Save To Your Account