The event source of keyboard events is generally related to the betting component. When a component is in an active state, a keyboard event will occur when a key on the keyboard is pressed, released, or tapped. The interface of keyboard events is KeyListener, and the method to register a keyboard event monitor is addKeyListener (monitor). There are 3 KeyListener interfaces implemented:
The class that manages keyboard events is KeyEvent, which provides methods:
public int getKeyCode(), get the key code pressed, and the key code table is defined in the KeyEvent class.
[Example] The applet has a button and a text area, which serves as the source of the event where the keyboard event occurs, and monitors it. When the program is running, click the button first to let the button activate. When entering English letters later, the entered letters will be displayed in the text area. When the letters are displayed, the letters are separated by space characters, and when there are 10 letters, the line break is displayed.
import java.applet.*import java.awt.*;import java.awt.event.*;public class Example6_10 extends Applet implements KeyListener{ int count =0; B utton 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 keyTyp ed(KeyEvent e){} public void keyReleased(KeyEvent e){}}