KeyListener和KeyEvent : 键盘事件监听 « Swing事件 « Java 教程

En
Java 教程
1. 语言基础
2. 数据类型
3. 操作符
4. 流程控制
5. 类定义
6. 开发相关
7. 反射
8. 正则表达式
9. 集合
10. 线
11. 文件
12. 泛型
13. 本土化
14. Swing
15. Swing事件
16. 二维图形
17. SWT
18. SWT 二维图形
19. 网络
20. 数据库
21. Hibernate
22. JPA
23. JSP
24. JSTL
25. Servlet
26. Web服务SOA
27. EJB3
28. Spring
29. PDF
30. 电子邮件
31. 基于J2ME
32. J2EE应用
33. XML
34. 设计模式
35. 日志
36. 安全
37. Apache工具
38. 蚂蚁编译
39. JUnit单元测试
Java
Java 教程 » Swing事件 » 键盘事件监听 
15. 21. 5. KeyListener和KeyEvent
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * KeyEventDemo
 */

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class KeyEventDemo extends JFrame implements KeyListener, ActionListener {
  JTextArea displayArea;
  JTextField typingArea;
  static final String newline = System.getProperty("line.separator");

  public static void main(String[] args) {
    /* Use an appropriate Look and Feel */
    try {
      // UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
      // UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
      UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    catch (UnsupportedLookAndFeelException ex) {
      ex.printStackTrace();
    catch (IllegalAccessException ex) {
      ex.printStackTrace();
    catch (InstantiationException ex) {
      ex.printStackTrace();
    catch (ClassNotFoundException ex) {
      ex.printStackTrace();
    }
    /* Turn off metal's use of bold fonts */
    UIManager.put("swing.boldMetal", Boolean.FALSE);

    // Schedule a job for event dispatch thread:
    // creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }

  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    // Create and set up the window.
    KeyEventDemo frame = new KeyEventDemo("KeyEventDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Set up the content pane.
    frame.addComponentsToPane();

    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }

  private void addComponentsToPane() {

    JButton button = new JButton("Clear");
    button.addActionListener(this);

    typingArea = new JTextField(20);
    typingArea.addKeyListener(this);

    // Uncomment this if you wish to turn off focus
    // traversal. The focus subsystem consumes
    // focus traversal keys, such as Tab and Shift Tab.
    // If you uncomment the following line of code, this
    // disables focus traversal and the Tab events will
    // become available to the key event listener.
    // typingArea.setFocusTraversalKeysEnabled(false);

    displayArea = new JTextArea();
    displayArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(displayArea);
    scrollPane.setPreferredSize(new Dimension(375125));

    getContentPane().add(typingArea, BorderLayout.PAGE_START);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(button, BorderLayout.PAGE_END);
  }

  public KeyEventDemo(String name) {
    super(name);
  }

  /** Handle the key typed event from the text field. */
  public void keyTyped(KeyEvent e) {
    displayInfo(e, "KEY TYPED: ");
  }

  /** Handle the key pressed event from the text field. */
  public void keyPressed(KeyEvent e) {
    displayInfo(e, "KEY PRESSED: ");
  }

  /** Handle the key released event from the text field. */
  public void keyReleased(KeyEvent e) {
    displayInfo(e, "KEY RELEASED: ");
  }

  /** Handle the button click. */
  public void actionPerformed(ActionEvent e) {
    // Clear the text components.
    displayArea.setText("");
    typingArea.setText("");

    // Return the focus to the typing area.
    typingArea.requestFocusInWindow();
  }

  /*
   * We have to jump through some hoops to avoid trying to print non-printing
   * characters such as Shift. (Not only do they not print, but if you put them
   * in a String, the characters afterward won't show up in the text area.)
   */
  private void displayInfo(KeyEvent e, String keyStatus) {

    // You should only rely on the key char if the event
    // is a key typed event.
    int id = e.getID();
    String keyString;
    if (id == KeyEvent.KEY_TYPED) {
      char c = e.getKeyChar();
      keyString = "key character = '" + c + "'";
    else {
      int keyCode = e.getKeyCode();
      keyString = "key code = " + keyCode + " (" + KeyEvent.getKeyText(keyCode)
          ")";
    }

    int modifiersEx = e.getModifiersEx();
    String modString = "extended modifiers = " + modifiersEx;
    String tmpString = KeyEvent.getModifiersExText(modifiersEx);
    if (tmpString.length() 0) {
      modString += " (" + tmpString + ")";
    else {
      modString += " (no extended modifiers)";
    }

    String actionString = "action key? ";
    if (e.isActionKey()) {
      actionString += "YES";
    else {
      actionString += "NO";
    }

    String locationString = "key location: ";
    int location = e.getKeyLocation();
    if (location == KeyEvent.KEY_LOCATION_STANDARD) {
      locationString += "standard";
    else if (location == KeyEvent.KEY_LOCATION_LEFT) {
      locationString += "left";
    else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
      locationString += "right";
    else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
      locationString += "numpad";
    else // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
      locationString += "unknown";
    }

    displayArea.append(keyStatus + newline + "    " + keyString + newline
        "    " + modString + newline + "    " + actionString + newline
        "    " + locationString + newline);
    displayArea.setCaretPosition(displayArea.getDocument().getLength());
  }
}
15. 21. 键盘事件监听
15. 21. 1. KeyListener接口
15. 21. 2. 事件ID和KeyEvent类定义
15. 21. 3. 如何撰写键盘事件监听
15. 21. 4. 键盘事件键盘事件
15. 21. 5. KeyListener和KeyEvent
15. 21. 6. 处理按键
15. 21. 7. Get key pressed as a key character (which is a Unicode character)
15. 21. 8. 键代码
15. 21. 9. 设置焦点遍历
15. 21. 10. 列出了键盘操
15. 21. 11. 使ENTER键像TAB键
15. 21. 12. Overriding Many Default Typed Key Bindings in a JTextComponent
www.java2java.com | Contact Us
Copyright 2010 - 2030 Java Source and Support. All rights reserved.
All other trademarks are property of their respective owners.