This section presents the KeyListener interface for handling key events. Key events are generated when keys on the keyboard are pressed and released. A class that implements KeyListener must provide declarations for methods keyPressed, keyReleased and keyTyped, each of which receives a KeyEvent as its argument. Class KeyEvent is a subclass of InputEvent. Method keyPressed is called in response to pressing any key. Method keyTyped is called in response to pressing any key that is not an action key. (The action keys are any arrow key, Home, End, Page Up, Page Down, any function key, Num Lock, Print Screen, Scroll Lock, Caps Lock and Pause.) Method keyReleased is called when the key is released after any keyPressed or keyTyped event.
The application of Fig. 11.36 and Fig. 11.37 demonstrates the KeyListener methods. Class KeyDemo implements the KeyListener interface, so all three methods are declared in the application.
Figure 11.36. Key event handling.
(This item is displayed on pages 564 - 565 in the print version)
1 // Fig. 11.36: KeyDemoFrame.java 2 // Demonstrating keystroke events. 3 import java.awt.Color; 4 import java.awt.event.KeyListener; 5 import java.awt.event.KeyEvent; 6 import javax.swing.JFrame; 7 import javax.swing.JTextArea; 8 9 public class KeyDemoFrame extends JFrame implements KeyListener 10 { 11 private String line1 = ""; // first line of textarea 12 private String line2 = ""; // second line of textarea 13 private String line3 = ""; // third line of textarea 14 private JTextArea textArea; // textarea to display output 15 16 // KeyDemoFrame constructor 17 public KeyDemoFrame() 18 { 19 super( "Demonstrating Keystroke Events" ); 20 21 textArea = new JTextArea( 10, 15 ); // set up JTextArea 22 textArea.setText( "Press any key on the keyboard..." ); 23 textArea.setEnabled( false ); // disable textarea 24 textArea.setDisabledTextColor( Color.BLACK ); // set text color 25 add( textArea ); // add textarea to JFrame 26 27 addKeyListener( this ); // allow frame to process key events 28 } // end KeyDemoFrame constructor 29 30 // handle press of any key 31 public void keyPressed( KeyEvent event ) 32 { 33 line1 = String.format( "Key pressed: %s", 34 event.getKeyText( event.getKeyCode() ) ); // output pressed key 35 setLines2and3( event ); // set output lines two and three 36 } // end method keyPressed 37 38 // handle release of any key 39 public void keyReleased( KeyEvent event ) 40 { 41 line1 = String.format( "Key released: %s", 42 event.getKeyText( event.getKeyCode() ) ); // output released key 43 setLines2and3( event ); // set output lines two and three 44 } // end method keyReleased 45 46 // handle press of an action key 47 public void keyTyped( KeyEvent event ) 48 { 49 line1 = String.format( "Key typed: %s", event.getKeyChar() ); 50 setLines2and3( event ); // set output lines two and three 51 } // end method keyTyped 52 53 // set second and third lines of output 54 private void setLines2and3( KeyEvent event ) 55 { 56 line2 = String.format( "This key is %san action key", 57 ( event.isActionKey() ? "" : "not " ) ); 58 59 String temp = event.getKeyModifiersText( event.getModifiers() ); 60 61 line3 = String.format( "Modifier keys pressed: %s", 62 ( temp.equals( "" ) ? "none" : temp ) ); // output modifiers 63 64 textArea.setText( String.format( "%s %s %s ", 65 line1, line2, line3 ) ); // output three lines of text 66 } // end method setLines2and3 67 } // end class KeyDemoFrame |
Figure 11.37. Test class for KeyDemoFrame.
(This item is displayed on pages 565 - 566 in the print version)
1 // Fig. 11.37: KeyDemo.java 2 // Testing KeyDemoFrame. 3 import javax.swing.JFrame; 4 5 public class KeyDemo 6 { 7 public static void main( String args[] ) 8 { 9 KeyDemoFrame keyDemoFrame = new KeyDemoFrame(); 10 keyDemoFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 11 keyDemoFrame.setSize( 350, 100 ); // set frame size 12 keyDemoFrame.setVisible( true ); // display frame 13 } // end main 14 } // end class KeyDemo |
The constructor (Fig. 11.36, lines 1728) registers the application to handle its own key events by using method addKeyListener at line 27. Method addKeyListener is declared in class Component, so every subclass of Component can notify KeyListener objects of key events for that Component.
At line 25, the constructor adds JTextArea textArea (where the application's output is displayed) to the JFrame. Notice in the screen captures that textArea occupies the entire window. This is due to the JFrame's default BorderLayout (discussed in Section 11.17.2 and demonstrated in Fig. 11.41). When a single Component is added to a BorderLayout, the Component occupies the entire Container. Note that line 24 uses method setDisabledTextColor to change the color of the text in the text area to black.
Methods keyPressed (lines 3136) and keyReleased (lines 3944) use KeyEvent method getKeyCode to get the virtual key code of the key that was pressed. Class KeyEvent maintains a set of constantsthe virtual key-code constantsthat represents every key on the keyboard. These constants can be compared with the return value of getKeyCode to test for individual keys on the keyboard. The value returned by getKeyCode is passed to KeyEvent method getKeyText, which returns a string containing the name of the key that was pressed. For a complete list of virtual key constants, see the on-line documentation for class KeyEvent (package java.awt.event). Method keyTyped (lines 4751) uses KeyEvent method getKeyChar to get the Unicode value of the character typed.
All three event-handling methods finish by calling method setLines2and3 (lines 5466) and passing it the KeyEvent object. This method uses KeyEvent method isActionKey (line 57) to determine whether the key in the event was an action key. Also, InputEvent method getModifiers is called (line 59) to determine whether any modifier keys (such as Shift, Alt and Ctrl ) were pressed when the key event occurred. The result of this method is passed to KeyEvent method getKeyModifiersText, which produces a string containing the names of the pressed modifier keys.
[Note: If you need to test for a specific key on the keyboard, class KeyEvent provides a key constant for every key on the keyboard. These constants can be used from the key event handlers to determine whether a particular key was pressed. Also, to determine whether the Alt, Ctrl, Meta and Shift keys are pressed individually, InputEvent methods isAltDown, isControlDown, isMetaDown and isShiftDown each return a boolean indicating if the particular key was pressed during the key event.]
Introduction to Computers, the Internet and the World Wide Web
Introduction to Java Applications
Introduction to Classes and Objects
Control Statements: Part I
Control Statements: Part 2
Methods: A Deeper Look
Arrays
Classes and Objects: A Deeper Look
Object-Oriented Programming: Inheritance
Object-Oriented Programming: Polymorphism
GUI Components: Part 1
Graphics and Java 2D™
Exception Handling
Files and Streams
Recursion
Searching and Sorting
Data Structures
Generics
Collections
Introduction to Java Applets
Multimedia: Applets and Applications
GUI Components: Part 2
Multithreading
Networking
Accessing Databases with JDBC
Servlets
JavaServer Pages (JSP)
Formatted Output
Strings, Characters and Regular Expressions
Appendix A. Operator Precedence Chart
Appendix B. ASCII Character Set
Appendix C. Keywords and Reserved Words
Appendix D. Primitive Types
Appendix E. (On CD) Number Systems
Appendix F. (On CD) Unicode®
Appendix G. Using the Java API Documentation
Appendix H. (On CD) Creating Documentation with javadoc
Appendix I. (On CD) Bit Manipulation
Appendix J. (On CD) ATM Case Study Code
Appendix K. (On CD) Labeled break and continue Statements
Appendix L. (On CD) UML 2: Additional Diagram Types
Appendix M. (On CD) Design Patterns
Appendix N. Using the Debugger
Inside Back Cover