Introduction to keyboard event design in Java graphical programming

  • 2020-04-01 04:15:35
  • OfStack

The event source of keyboard events is generally related to the begging component. When a component is active, a keyboard event occurs when a key on the keyboard is pressed, released, or struck. The interface for keyboard events is KeyListener, and the method to register the keyboard event monitor is addKeyListener. The KeyListener interface is implemented in three ways:

KeyPressed: a key on the keyboard is pressed; KeyReleased: a key on the keyboard was pressed and released; KeyPressed (KeyEvent e) : combination of the two methods keyPressed and keyReleased.

The class that manages keyboard events is KeyEvent, which provides methods:
Public int getKeyCode(), get the key code of the press, and the key code table is defined in the KeyEvent class.

Applet has a button and a text area that ACTS as the event source for keyboard events and monitors it. While the program is running, click the button to activate it. When typing English letters later, the input letters are displayed in the body area. When letters are displayed, they are separated by Spaces, and when they are full of 10 letters, the newline 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){}
}


Related articles: