Event sources for keyboard events are generally beggar component-related, and when a component is active, a keyboard event occurs when a key is pressed, released, or tapped on the keyboard. The interface for keyboard events is KeyListener, and the way to register the keyboard event monitor is Addkeylistener (monitor). There are 3 implementations of the KeyListener interface:
- keypressed (KeyEvent E): A key on the keyboard is pressed;
- keyreleased (KeyEvent E): A key on the keyboard is pressed and released;
- keytyped (KeyEvent e): A combination of keypressed and keyreleased two methods.
The class that manages keyboard events is KeyEvent, which provides methods:
public int getKeyCode (), obtains the pressed key code, the key Code table is defined in the KeyEvent class.
The example applet has a button and a text area, and the button acts as the source of the event that the keyboard event occurs and monitors it. When the program is running, click on the button first to activate the button. When you enter an English letter later, the letter is displayed in the body area. When the letters are displayed, the letters are separated by spaces, and when they are full 10 letters, the line wrap is displayed.
Import java.applet.*
import java.awt.*;
Import java.awt.event.*;
public class Example6_10 extends Applet implements keylistener{
int count =0;
Button button = New button ();
TextArea Text = new TextArea (5,20);
public void init () {
button.addkeylistener (this);
Add (Button); Add (text);
public void keypressed (KeyEvent e) {
int t = E.getkeycode ();
if (t>=keyevent.vk_a&&t<=keyevent.vk_z) {
text.append ((char) t+ "");
count++;
if (count%10==0)
text.append ("\ n")
;
}
public void keytyped (KeyEvent e) {} public
void keyreleased (KeyEvent e) {}
}