Keyboard actions can also be used in modern windows applications to trigger events. Events for Keyboard actions are handled by the KeyListener Class.
Event Listener
KeyListener
Because there are no visible objects associated with keyboard actions, there is no need to create and declare keyboard objects.
The only thing that needs to be done is to create a listener associated with the applet:
eg.
this.addKeyListener(this);
KeyListener
The event handlers for the KeyListener class are:
void keyTyped(KeyEvent e) - Invoked when a key has been typed.
void keyPressed(KeyEvent e) - Invoked when a key has been pressed.
void keyReleased(KeyEvent e) - Invoked when a key has been released.
Sample Applet
Note: you will need to click in the applet window to activate the key listener for the applet.
import java.awt.*; import java.applet.*; import java.awt.event.*; public class KeyEventSample extends Applet implements KeyListener { boolean released, pressed; public void init() { this.addKeyListener(this); } public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { pressed=true; released=false; repaint(); } public void keyReleased(KeyEvent e) { released=true; pressed=false; repaint(); } public void paint(Graphics g) { if(pressed) g.drawString("Key Pressed", 100, 100 ); if(released) g.drawString("Key Released", 100, 100 ); } }
For a complete listing of keyboard events see:
Project 7