Home > Java > javaTutorial > Introduction to keyboard event design in Java graphical programming

Introduction to keyboard event design in Java graphical programming

高洛峰
Release: 2017-01-17 16:16:41
Original
1321 people have browsed it

The event source of keyboard events is generally related to components. When a component is activated, a keyboard event will occur when a key on the keyboard is pressed, released, or tapped. The interface for keyboard events is KeyListener, and the method for registering a keyboard event monitor is addKeyListener(monitor). There are three KeyListener interfaces:

keyPressed(KeyEvent e): a key on the keyboard is pressed;

keyReleased(KeyEvent e): a key on the keyboard is pressed, and Release;

keyTyped(KeyEvent e): a combination of keyPressed and keyReleased methods.

The class that manages keyboard events is KeyEvent. This class provides methods:
public int getKeyCode() to obtain the pressed key code. The key code table is defined in the KeyEvent class.

[Example] The applet has a button and a text area. The button serves as the event source for keyboard events and monitors it. When the program is running, click the button first to activate the button. When you enter English letters in the future, the entered letters will be displayed in the text area. When letters are displayed, they are separated by spaces, and when there are 10 letters, they are displayed in new lines.

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){}
}
Copy after login

For more articles related to the introduction of keyboard event design in Java graphical programming, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template