General background information
In the past few lessons, you have learned how to handle mouse events under a variety of circumstances. Up to this point, however, I haven't discussed much if anything about keyboard events.
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 object that 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.
Preview
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 Player plug-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.
KeyboardEvent02 output at startup. |
---|
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 program is 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.
KeyboardEvent02 output after clicking the Canvas and pressing a key. |
---|
The output
As you can see, this caused the letter "a" to be displayed in a large font size in the 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.
Discussion and sample code
The project file structure
The final project file structure, captured from the FlashDevelop project window, is shown in Figure 3.
Project file structure for KeyboardEvent02. |
---|
Will explain in fragments
I will explain the code for this program in fragments. Complete listings of the MXML code and the ActionScript code are provided in Listing 6 and Listing 7 near the end of the lesson.
The MXML code
The MXML code is shown in Listing 1 and again in Listing 6 near the end of the lesson.
LISTING 1: Code for the file named Main.mxml.
<?xml version="1.0" encoding="utf-8"?>
<!--
KeyboardEvent02
See explanation in the file named Driver.as
-->
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:cc="CustomClasses.*">
<cc:Driver/>
</mx:Application>
As is often the case in this series of lessons, the MXML file is very simple because the program was coded almost entirely in ActionScript. The MXML code simply instantiates an object of the Driver class. From that point forward, the behavior of the program is controlled by ActionScript code.
The ActionScript code
Beginning of the Driver class
The driver class begins in Listing 2.
LISTING 2: Beginning of the Driver Class.
/*KeyboardEvent02 06/03/10
Illustrates the use of KeyboardEvent, charCode values,
absolute positioning on a Canvas object, focus, and a
TextArea object among other things.
See http://livedocs.adobe.com/flex/3/langref/flash/events
/KeyboardEvent.html
*********************************************************/
package CustomClasses{
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import mx.containers.Canvas;
import mx.controls.Label;
import mx.controls.TextArea;
public class Driver extends Canvas{
//Instantiate and save references to the
// objects needed by the program.
private var instrArea:TextArea = new TextArea();
private var targetLabel:Label = new Label();
private var canvasLabel:Label = new Label();
Extending the Canvas class
With the possible exception of the fact that the Driver class extends the Canvas class, there is nothing new in Listing 2. An object of the Driver class is a Canvas object.
I elected to extend the Canvas class because this makes it possible to position objects added as children of that class using absolute location coordinates.
The constructor for the Driver class
The constructor is shown in its entirety in Listing 3.
LISTING 3: The constructor for the Driver class.
public function Driver() {//constructor
//Set the size of the Canvas object.
this.width = 300;
this.height = 120;
//Prepare the TextArea and the labels.
canvasLabel.text = "This is a 300x120 Canvas";
instrArea.text = "First click the yellow canvas "
+ "with the mouse\nThen press a key to display "
+ "the character.";
instrArea.width = 298;
instrArea.height = 40;
instrArea.x = 1;
instrArea.y = 26;
targetLabel.setStyle("fontSize", 30);
targetLabel.x = 10;
targetLabel.y = 78
//Display an empty string at startup.
targetLabel.text = "";
//Add the labels and TextArea to the Canvas.
this.addChild(canvasLabel);
this.addChild(instrArea);
this.addChild(targetLabel);
//Set the Canvas background color to yellow.
this.setStyle("backgroundColor", "0xFFFF00");
//Register two event listeners on the canvas.
this.addEventListener(
MouseEvent.CLICK, clickHandler);
this.addEventListener(
KeyboardEvent.KEY_DOWN,eventHandler);
} //end constructor
There are several things in Listing 3 that deserve an explanation beyond the embedded comments.
Set the size
The constructor in Listing 3 begins by setting the width and height properties of the Canvas object to set the overall dimensions of the object in pixels.
Set the text for the upper-left Label object
The constructor sets the text property of the Label object referred to by canvasLabel to the small text shown in the upper-left corner of Figure 1. Since the x and y coordinate values for this object are not purposely set, they will each have a default value of zero. This will cause them to be placed in the upper-left corner of the canvas as shown in Figure 1.
Set various properties for the TextArea object
Then the constructor sets various property values for the TextArea object, including its text, its dimensions, and its location coordinates. As I mentioned earlier, the sole purpose of this object in this program is to provide operating instructions.
Set various properties for the target Label object
The Label object that is referred to by targetLabel in Listing 3 is used to display the character for the key that is pressed as shown by the large lower-case "a" in Figure 2.
The constructor sets various properties for this object including a font size of 30 points and an initial string value that is an empty string.
Add the objects to the Canvas
Then the constructor calls the addChild method on the Canvas object three times in succession to add the three objects to the canvas in the locations specified by their location coordinates.
Set the background color to yellow
The constructor sets the background color of the canvas to yellow. Otherwise, it would be indistinguishable from the gray background color of the Flash window.
Register event listeners
Finally, the constructor registers two event listeners on the Canvas object.
A MouseEvent.CLICK listener
The first event listener that is registered is one that will handle events of the type MouseEvent.CLICK . As you will see shortly, this handler causes the Canvas object to gain the focus when the user clicks the canvas with the mouse.
A KeyboardEvent.KEY_DOWN listener
The second listener that is registered is one that will handle events of the type KeyboardEvent.KEY_DOWN and display the character for the key that is pressed as shown by the large lower-case "a" in Figure 2.
The MouseEvent.CLICK listener
This listener is shown in its entirety in Listing 4.
LISTING 4: The MouseEvent.CLICK listener.
private function clickHandler(event:MouseEvent):void {
stage.focus = this;
}//end clickHandler
As I explained earlier, the sole purpose of this event listener is to make it possible for the user to cause the yellow canvas object to gain the focus.
Rather than attempt to explain the one statement in the method in Listing 4, I will refer you to the page in the Adobe documentation that explains it.
The KeyboardEvent.KEY_DOWN listener
The method shown in Listing 5 is executed each time any key is pressed. However, some of the keys, such as the shift key, aren't represented by a character that can be displayed.
LISTING 5: The KeyboardEvent.KEY_DOWN listener.
private function eventHandler(
event:KeyboardEvent):void {
targetLabel.text =
String.fromCharCode(event.charCode);
} //end eventHandler
The charCode property
Each time the method is called, it receives a reference to an object of type KeyboardEvent . This object encapsulates several types of information about the key that was pressed. One such piece of information is a property named charCode . Here is some of what the documentation has to say about this property:
"Contains the character code value of the key pressed or released. The character code values are English keyboard values. For example, if you press Shift+3, charCode is # on a Japanese keyboard, just as it is on an English keyboard."
The keyCode property
Another interesting property of the incoming object is the property named keyCode . This property can be used to identity any key on the keyboard, including those that are not represented by printable characters such as the shift key and the arrow keys.
Modify the text in targetLabel
The objective of the code in Listing 5 is to modify the text in the label referred to by targetLabel to cause it to reflect the character for the key that was pressed.
Convert charCode to a string
The text property of the label is type String . That means that the value of charCode must be converted to type String .
This is accomplished by calling the static fromCharCode method of the String class.
Because this is a static method, it can be called by joining its name to the name of the class to which it belongs: String .
Assign the returned String value to the text property
The method returns a reference to a String object containing the character whose charCode is passed as a parameter to the method. This string is then assigned to the textproperty of the target label, producing the output shown in Figure 2.
Run the program
I encourage you to run this program from the web. Then copy the code from Listing 6 and Listing 7. Use that code to create your own project. Compile and run the project. Experiment with the code, making changes, and observing the results of your changes. Make certain that you can explain why your changes behave as they do.
Resources
I will publish a list containing links to ActionScript resources as a separate document. Search for ActionScript Resources in the Connexions search box.
Complete program listings
Complete listings of the programs discussed in this lesson are provided below.
LISTING 6: Code for the file named Main.mxml.
<?xml version="1.0" encoding="utf-8"?>
<!--
KeyboardEvent02
See explanation in the file named Driver.as
-->
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:cc="CustomClasses.*">
<cc:Driver/>
</mx:Application>
LISTING 7: Source code for the class named Driver.
/*Prob04 06/03/10
Illustrates the use of KeyboardEvent, charCode values,
absolute positioning on a Canvas object, focus, and a
TextArea object among other things.
See http://livedocs.adobe.com/flex/3/langref/flash/events
/KeyboardEvent.html
*********************************************************/
package CustomClasses{
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import mx.containers.Canvas;
import mx.controls.Label;
import mx.controls.TextArea;
public class Driver extends Canvas{
//Instantiate and save references to the
// objects needed by the program.
private var instrArea:TextArea = new TextArea();
private var targetLabel:Label = new Label();
private var canvasLabel:Label = new Label();
//--------------------------------------------------//
public function Driver() {//constructor
//Set the size of the Canvas object.
this.width = 300;
this.height = 120;
//Prepare the TextArea and the labels.
canvasLabel.text = "This is a 300x120 Canvas";
instrArea.text = "First click the yellow canvas "
+ "with the mouse\nThen press a key to display "
+ "the character.";
instrArea.width = 298;
instrArea.height = 40;
instrArea.x = 1;
instrArea.y = 26;
targetLabel.setStyle("fontSize", 30);
targetLabel.x = 10;
targetLabel.y = 78
//Display an empty string at startup.
targetLabel.text = "";
//Add the labels and TextArea to the Canvas.
this.addChild(canvasLabel);
this.addChild(instrArea);
this.addChild(targetLabel);
//Set the Canvas background color to yellow.
this.setStyle("backgroundColor", "0xFFFF00");
//Register two event listeners on the canvas.
this.addEventListener(
MouseEvent.CLICK, clickHandler);
this.addEventListener(
KeyboardEvent.KEY_DOWN,eventHandler);
} //end constructor
//--------------------------------------------------//
//This method is executed when any key is pressed.
// Note, however, that some keys, such as the shift
// key, don't have displayable charCode values.
private function eventHandler(
event:KeyboardEvent):void {
targetLabel.text =
String.fromCharCode(event.charCode);
} //end eventHandler
//--------------------------------------------------//
//This event handler is required to cause the Canvas
// to gain the focus and respond to keyboard events.
// See the URL listed earlier. (Note that focus can
// also be gained by pressing the tab key.)
private function clickHandler(event:MouseEvent):void {
stage.focus = this;
}//end clickHandler
//--------------------------------------------------//
} //end class
} //end package
No comments:
Post a Comment