Java. Unit 4pptx
Java. Unit 4pptx
Event Handling
Handling Keyboard Events
• To handle the keyboard events we will have to implement the
KeyListener interface.
• When a key is pressed, a KEY_PRESSED event is generated. This
results in a call to the keyPressed( ) event handler. When the key is
released, a KEY_RELEASED event is generated and the keyReleased( )
handler is executed. If a character is generated by the keystroke, then
a KEY_TYPED event is sent and the keyTyped( ) handler is invoked.
• The following program demonstrates keyboard input. It echoes
keystrokes to the window and shows the pressed/released status of
each key.
import java.awt.*;
import java.awt.event.*;
public class SimpleKey extends Frame implements
KeyListener{
String msg = "";
String keyState = "";
public SimpleKey(){
addKeyListener(this);
addWindowListener(new MyWindowAdapter());
}
// handle a key press
public void keyPressed(KeyEvent ke){
keyState = "Key down";
repaint();
}
// handle a key release
public void keyReleased(KeyEvent ke){
keyState = "Key up";
repaint();
}
// handle a key typed
public void keyTyped(KeyEvent ke){
msg += ke.getKeyChar();
repaint();
}
// display keystrokes
public void paint(Graphics g){
g.drawString(msg, 20, 100);
g.drawString(keyState, 20, 50);
}