<< Chapter < Page | Chapter >> Page > |
Handling keyboard events differs from handling mouse events in one major respect -- focus.
What is focus?
At any instant in time, only one object in only one application of potentially many running applications can have the focus. The objectthat has the focus is the only object that can respond to the keyboard. Therefore, before an object can fire events of type KeyboardEvent , that object must have the focus.
There is more than one way to cause an object to gain the focus. I will show you one way in this lesson. Then I will show you how to handle events of type KeyboardEvent fired by that object.
Run the ActionScript program named KeyboardEvent02
If you have the Flash Player plug-in (version 10 or later) installed in your browser, click here to run the program that I will explain in this lesson.
If you don't have the proper Flash Player installed, you should be notified of that fact and given an opportunity to download and install the Flash Playerplug-in program.
Program output as startup
The image in Figure 1 is similar to what you should see in your browser when you start the program named KeyboardEvent02 running.
The objects
The yellow rectangle in Figure 1 is a Canvas object with a yellow background color.
The text in the upper-left corner is the text on a Label object.
The text in the white rectangle is text in an object of the class TextArea . This object allows the user to enter text, but that isn't the purpose of the object in this program. The purpose of the object in this programis simply to provide an output consisting of multi-line operating instructions.
The operating instructions
At startup, the program will not respond to keyboard input. Clicking the yellow Canvas object with the mouse causes it to gain the focus. Once it has the focus, the canvas will respond to keyboard input.
Output after clicking the Canvas and pressing a key
Figure 2 shows the program output after clicking the yellow Canvas object with the mouse and then pressing the "a" key.
The output
As you can see, this caused the letter "a" to be displayed in a large font size inthe lower-left corner of the canvas. This will work for any of the letter or number keys, with or without holding down the shift key. Other keys,such as the arrow keys, don't produce a visible output however.
The project file structure
The final project file structure, captured from the FlashDevelop project window, is shown in Figure 3.
Will explain in fragments
I will explain the code for this program in fragments. Complete listings of the MXML code and theActionScript code are provided in Listing 6 and Listing 7 near the end of the lesson.
The MXML code is shown in Listing 1 and again in Listing 6 near the end of the lesson.
Notification Switch
Would you like to follow the 'Object-oriented programming (oop) with actionscript' conversation and receive update notifications?