// KeyboardInputDemoApplet.java (c) Kari Laitinen // http://www.naturalprogramming.com // 2006-10-12 File created. // 2009-11-07 Latest modification. // This program shows how a Java program can find out which keys // are pressed on the keyboard. import java.awt.* ; import java.awt.event.* ; import javax.swing.* ; public class KeyboardInputDemoApplet extends JApplet implements KeyListener { Font large_font = new Font( "SansSerif", Font.BOLD, 24 ) ; int code_of_last_pressed_key = '?' ; public void init() { addKeyListener( this ) ; } public void keyPressed( KeyEvent event ) { code_of_last_pressed_key = event.getKeyCode() ; repaint() ; System.out.print( "\n Method keyPressed() was called. Key code = " + code_of_last_pressed_key ) ; } public void keyReleased( KeyEvent event ) { System.out.print( "\n Method keyReleased() was called." ) ; } public void keyTyped( KeyEvent event ) { System.out.print( "\n Method keyTyped() was called." ) ; } public void paint( Graphics graphics ) { super.paint( graphics ) ; graphics.setFont( large_font ) ; // The following statement prints the code of the last pressed key // as character, as hexadecimal code, and as decimal code. graphics.drawString( String.format( "Last pressed key: %c %X %d", code_of_last_pressed_key, code_of_last_pressed_key, code_of_last_pressed_key ), 100, 200 ) ; // The KeyEvent class provides predefined constants (e.g. VK_F1) // which can be used to refer to the individual keys on the keyboard. if ( code_of_last_pressed_key == KeyEvent.VK_F1 ) { graphics.drawString( "You pressed the F1 key", 100, 250 ) ; } else if ( code_of_last_pressed_key == KeyEvent.VK_UP ) { graphics.drawString( "You pressed the Arrow Up key", 100, 250 ) ; } else if ( code_of_last_pressed_key == KeyEvent.VK_DOWN ) { graphics.drawString( "You pressed the Arrow Down key", 100, 250 ) ; } // A window has 'focus' when keyboard input is directed to it. // The following statement ensures that the applet window will // receive keyboard input. if ( ! hasFocus() ) { requestFocus() ; } } }