- Listening for Events
- Mouse Detection
- The SimpleButton Class
- Invisible Buttons
- Animated Buttons and the Movie Clip Symbol
- Complex Buttons
- Button-tracking Options
- Changing Button Behavior
- Creating Buttons Dynamically
- Keyboard Detection
- The Contextual Menu
- Creating Continuous Actions
- A Summary of Events
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
- Select the first frame of the Timeline, and open the Actions panel.
- 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(); myup.graphics.beginFill(0xff4000); myup.graphics. drawCircle(100,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.
- Create three more new shapes with different colors in the same manner .
These four shapes will be assigned to the four keyframes of the new button.
- In the next line, instantiate a new button from the SimpleButton class, like so:
var mybutton:SimpleButton = new SimpleButton();
- 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;
- To see the new button on the Stage, you must add it to the Stage to be displayed with the following code:
stage.addChild(mybutton);
To see any dynamically generated graphic, you always need to use the method addChild(). The full Action-Script code can be seen in .
- Test your movie by choosing Control > Test Movie > in Flash Professional .