Introduction to keyboard event design in Java graphical programming _java

Source: Internet
Author: User

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:

    1. keypressed (KeyEvent E): A key on the keyboard is pressed;
    2. keyreleased (KeyEvent E): A key on the keyboard is pressed and released;
    3. 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) {}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.