Skip to content Skip to navigation

OpenStax_CNX

You are here: Home » Content » Handling Keyboard Events

Navigation

Recently Viewed

This feature requires Javascript to be enabled.
 

Handling Keyboard Events

Module by: R.G. (Dick) Baldwin. E-mail the author

Summary: Learn about focus and keyboard events.

Note:

Click KeyboardEvent02 to run the ActionScript program from this lesson. (Click the "Back" button in your browser to return to this page.)

Preface

General

This tutorial lesson is part of a series of lessons dedicated to object-oriented programming (OOP) with ActionScript.

Note:

All references to ActionScript in this lesson are references to version 3.0 or later.

Several ways to create and launch ActionScript programs

There are several ways to create and launch programs written in the ActionScript programming language. Many of the lessons in this series will use Adobe Flex as the launch pad for the sample ActionScript programs.

An earlier lesson titled The Default Application Container provided information on how to get started programming with Adobe's Flex Builder 3. The lesson titled Using Flex 3 in a Flex 4 World was added later to accommodate the release of Flash Builder 4. (See Baldwin's Flex programming website .) You should study those lessons before embarking on the lessons in this series.

Some understanding of Flex MXML will be required

I also recommend that you study all of the lessons on Baldwin's Flex programming website in parallel with your study of these ActionScript lessons. Eventually you will probably need to understand both ActionScript and Flex and the relationships that exist between them in order to become a successful ActionScript programmer.

Will emphasize ActionScript code

It is often possible to use either ActionScript code or Flex MXML code to achieve the same result. Insofar as this series of lessons is concerned, the emphasis will be on ActionScript code even in those cases where Flex MXML code may be a suitable alternative.

Viewing tip

I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the figures and listings while you are reading about them.

Figures

  • Figure 1 . KeyboardEvent02 output at startup.
  • Figure 2 . KeyboardEvent02 output after clicking the Canvas and pressing a key.
  • Figure 3 . Project file structure for KeyboardEvent02.

Listings

Supplemental material

I recommend that you also study the other lessons in my extensive collection of online programming tutorials. You will find a consolidated index at www.DickBaldwin.com .

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.

Figure 1: KeyboardEvent02 output at startup.
KeyboardEvent02 output at startup.
Missing image

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.

Figure 2: KeyboardEvent02 output after clicking the Canvas and pressing a key.
KeyboardEvent02 output after clicking the Canvas and pressing a key.
Missing image

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.

Figure 3: Project file structure for KeyboardEvent02.
Project file structure for KeyboardEvent02.
Missing image

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 text property 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

Miscellaneous

This section contains a variety of miscellaneous materials.

Note:

Housekeeping material
  • Module name: Handling Keyboard Events
  • Files:
    • ActionScript0115\ActionScript0115.htm
    • ActionScript0115\Connexions\ActionScriptXhtml0115.htm

Note:

PDF disclaimer: Although the Connexions site makes it possible for you to download a PDF file for this module at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should be aware that some of the HTML elements in this module may not translate well into PDF.

-end-

Content actions

Download module as:

PDF | EPUB (?)

What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

Downloading to a reading device

For detailed instructions on how to download this content's EPUB to your specific device, click the "(?)" link.

| More downloads ...

Add module to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks