Home : Course Map : Chapter 12 : Java :
Handling Keystrokes
JavaTech
Course Map
Chapter 12

Printing
  Demo 1
Cursor Icons
  Demo 2
MouseButtons
  Demo 3
PopupMenu
  Demo 4
Keystrokes
  Demo 5
Audio
  Demo 6
Timing & Speed
  Demo 7
Toolkit
  Demo 8
AppletContext
  Demo 9
Exercises

    Supplements
Java Beans
More APIs
Java & Browsers
  Demo 1
     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

Just as you can catch the mouse buttons, you can also identify which keyboard button has been hit. In the example below, we create a KeyAdapter annoymous inner class and override the keyTyped(KeyEvent e) method. (These classes come in the java.awt.event package.)

The KeyListener interface, which KeyAdapter implements, provides the keyTyped method that recieves a KeyEvent when the user presses a key:

  public void keyTyped (KeyEvent e) {
     saySomething ("got " + e.getKeyChar (), e);
     ...

We see that the KeyEvent object can be used to obtain the key character with the getKeyChar() method.

The example KeyTestApplet holds an instance of a JPanel subclass called KeyTestPanel, which in turn holds a subpanel and a JTextArea. We add an instance of a KeyAdapter to the subpanel's list of KeyListener objects.

The subpanel is made focusable so that it can receive the key events. (When the applet runs, you should click on it and hit "tab" to put the focus on the subpanel.) The adapter sends each KeyEvent object to the keyTyped() method whenever the user presses a key

KeyTestApplet

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/** Demonstration of listening for key strokes.**/
public class KeyTestApplet extends JApplet
{
  public void init () {
    Container content_pane = getContentPane ();
    KeyTestPanel  key_test_panel = new KeyTestPanel ();
    content_pane.add (key_test_panel);
  } // init

} // class KeyTestApplet

/** A JPanel class that detects key strokes on one subpanel and
  * displays messages about them in a text area.
 **/
class KeyTestPanel extends JPanel {
  JTextArea fTextArea = null;

  /** Create an interface with a text area and a blank panel.
    * Key strokes while the panel has focus will be detected
    * and a message printed in the text area.
   **/
  KeyTestPanel () {

    setLayout (new GridLayout (2,1));
    JPanel canvas = new JPanel ();
    add (canvas, "North");
    canvas.setBackground (Color.YELLOW);

    fTextArea = new JTextArea ();
    fTextArea.setEditable (false);

    // Add to a scroll pane so that a long list of
    // keyinputs can be seen.
    JScrollPane area_scroll_pane = new JScrollPane (fTextArea);

    add (area_scroll_pane, "Center");

    // Add to the panel an anonymous KeyAdapter that will
    // respond to key strokes.
    canvas.addKeyListener (
      new KeyAdapter () {
        public void keyTyped (KeyEvent e) {
          saySomething ("got "+ e.getKeyChar (),e);
        }
      } // end anonymous class
    ); // end method call

    // Let the canvas get the focus.
    canvas.setFocusable (true);
  } // ctor

  /** Display a message in the text area about the key event.**/
  void saySomething (String eventDescription, KeyEvent e) {
    fTextArea.append (eventDescription + " on "
         + e.getComponent ().getClass ().getName () + "\n");
  } // saySomething

} // class KeyTestPanel

 

The KeyListener interface also has the keyPressed and keyRelease methods that fire a KeyEvent when a key is pressed and when it is released, respectively.

Combinations of keys can be detected by testing the key codes available from the KeyEvent class. Java assigns every key a virtual key code indicated by a VK_ prefix. For example:

   public void keyPressed (java.awt.event.KeyEvent e){
         int keyCode = e.getKeyCode();
         if( keyCode == KeyEvent.VK_LEFT && e.isShiftDown;
             ...     

which indicates that the left arrow and shift keys were simulataneously pressed.

The KeyEvent provides several other useful methods such as isActionKey() to indicate whether the event was triggered by one of the action keys such as HOME, END, etc.

See the KeyListener, KeyEvent API descriptions for more info on using key data.

References & Web Resources


Latest update: Dec.6, .2004

              Tech
Tech APIs
Exercises

           Physics
Math/Science APIs
JAIDA Program
  Demo 1
Demo 1 Discussion
Exercises

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.