Java Tutorial/Swing Event/KeyListener

Материал из Java эксперт
Версия от 15:18, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Demonstrates key events

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
class MyKeyListener implements KeyListener {
  public void keyTyped(KeyEvent e) {
    char c = e.getKeyChar();
    System.out.println("Key Typed: " + c);
  }
  public void keyPressed(KeyEvent e) {
    char c = e.getKeyChar();
    System.out.println("Key Pressed: " + c);
  }
  public void keyReleased(KeyEvent e) {
    char c = e.getKeyChar();
    System.out.println("Key Released: " + c);
  }
}
public class KeyListenerDemo {
  public static void main(String[] a) {
    JFrame frame = new JFrame("Popup JComboBox");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextField textField = new JTextField();
    textField.addKeyListener(new MyKeyListener());
    frame.add(textField);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





Get key pressed as a key character (which is a Unicode character)

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextField component = new JTextField();
    component.addKeyListener(new MyKeyListener());
    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
  }
}
class MyKeyListener extends KeyAdapter {
  public void keyPressed(KeyEvent evt) {
    if (evt.getKeyChar() == "a") {
      System.out.println("Check for key characters: " + evt.getKeyChar());
    }
    if (evt.getKeyCode() == KeyEvent.VK_HOME) {
      System.out.println("Check for key codes: " + evt.getKeyCode());
    }
  }
}





Get key pressed as a key code

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextField component = new JTextField();
    component.addKeyListener(new MyKeyListener());
    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
  }
}
class MyKeyListener extends KeyAdapter {
  public void keyPressed(KeyEvent evt) {
    if (evt.getKeyChar() == "a") {
      System.out.println("Check for key characters: " + evt.getKeyChar());
    }
    if (evt.getKeyCode() == KeyEvent.VK_HOME) {
      System.out.println("Check for key codes: " + evt.getKeyCode());
    }
  }
}





Handling Key Presses

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextField component = new JTextField();
    component.addKeyListener(new MyKeyListener());
    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
  }
}
class MyKeyListener extends KeyAdapter {
  public void keyPressed(KeyEvent evt) {
    if (evt.getKeyChar() == "a") {
      System.out.println("Check for key characters: " + evt.getKeyChar());
    }
    if (evt.getKeyCode() == KeyEvent.VK_HOME) {
      System.out.println("Check for key codes: " + evt.getKeyCode());
    }
  }
}





How to Write a Key Listener

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class UsingKeyListener {
  public static void main(String[] args) {
    JFrame aWindow = new JFrame("This is the Window Title");
    aWindow.setBounds(50, 100, 300, 300);
    aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextField typingArea = new JTextField(20);
    typingArea.addKeyListener(new KeyListener() {
      /** 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: ");
      }
      protected void displayInfo(KeyEvent e, String s) {
        String keyString, modString, tmpString, actionString, locationString;
        // You should only rely on the key char if the event
        // is a key typed event.
        int id = e.getID();
        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 modifiers = e.getModifiersEx();
        modString = "modifiers = " + modifiers;
        tmpString = KeyEvent.getModifiersExText(modifiers);
        if (tmpString.length() > 0) {
          modString += " (" + tmpString + ")";
        } else {
          modString += " (no modifiers)";
        }
        actionString = "action key? ";
        if (e.isActionKey()) {
          actionString += "YES";
        } else {
          actionString += "NO";
        }
        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";
        }
        System.out.println(keyString);
        System.out.println(modString);
        System.out.println(actionString);
        System.out.println(locationString);
      }
    });
    aWindow.add(typingArea);
    aWindow.setVisible(true);
  }
}





KeyListener and 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(375, 125));
    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());
  }
}





Listing the Key Bindings in a Component

import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.Action;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
public class Main {
  public static void main(String[] argv) throws Exception {
    JButton component = new JButton("button");
    InputMap map = component.getInputMap(JComponent.WHEN_FOCUSED);
    list(map, map.keys());
    list(map, map.allKeys());
  }
  static void list(InputMap map, KeyStroke[] keys) {
    if (keys == null) {
      return;
    }
    for (int i = 0; i < keys.length; i++) {
      keyStroke2String(keys[i]);
      while (map.get(keys[i]) == null) {
        map = map.getParent();
      }
      if (map.get(keys[i]) instanceof String) {
        String actionName = (String) map.get(keys[i]);
        System.out.println(actionName);
      } else {
        Action action = (Action) map.get(keys[i]);
        System.out.println(action);
      }
    }
  }
  static void keyStroke2String(KeyStroke key) {
    int m = key.getModifiers();
    if ((m & (InputEvent.SHIFT_DOWN_MASK | InputEvent.SHIFT_MASK)) != 0) {
      System.out.println("shift ");
    }
    if ((m & (InputEvent.CTRL_DOWN_MASK | InputEvent.CTRL_MASK)) != 0) {
      System.out.println("ctrl ");
    }
    if ((m & (InputEvent.META_DOWN_MASK | InputEvent.META_MASK)) != 0) {
      System.out.println("meta ");
    }
    if ((m & (InputEvent.ALT_DOWN_MASK | InputEvent.ALT_MASK)) != 0) {
      System.out.println("alt ");
    }
    if ((m & (InputEvent.BUTTON1_DOWN_MASK | InputEvent.BUTTON1_MASK)) != 0) {
      System.out.println("button1 ");
    }
    if ((m & (InputEvent.BUTTON2_DOWN_MASK | InputEvent.BUTTON2_MASK)) != 0) {
      System.out.println("button2 ");
    }
    if ((m & (InputEvent.BUTTON3_DOWN_MASK | InputEvent.BUTTON3_MASK)) != 0) {
      System.out.println("button3 ");
    }
    switch (key.getKeyEventType()) {
    case KeyEvent.KEY_TYPED:
      System.out.println("typed ");
      System.out.println(key.getKeyChar() + " ");
      break;
    case KeyEvent.KEY_PRESSED:
      System.out.println("pressed ");
      System.out.println(getKeyText(key.getKeyCode()) + " ");
      break;
    case KeyEvent.KEY_RELEASED:
      System.out.println("released ");
      System.out.println(getKeyText(key.getKeyCode()) + " ");
      break;
    default:
      System.out.println("unknown-event-type ");
      break;
    }
  }
  static String getKeyText(int keyCode) {
    if (keyCode >= KeyEvent.VK_0 && keyCode <= KeyEvent.VK_9 || keyCode >= KeyEvent.VK_A
        && keyCode <= KeyEvent.VK_Z) {
      return String.valueOf((char) keyCode);
    }
    switch (keyCode) {
    case KeyEvent.VK_COMMA:
      return "COMMA";
    case KeyEvent.VK_PERIOD:
      return "PERIOD";
    case KeyEvent.VK_SLASH:
      return "SLASH";
    case KeyEvent.VK_SEMICOLON:
      return "SEMICOLON";
    case KeyEvent.VK_EQUALS:
      return "EQUALS";
    case KeyEvent.VK_OPEN_BRACKET:
      return "OPEN_BRACKET";
    case KeyEvent.VK_BACK_SLASH:
      return "BACK_SLASH";
    case KeyEvent.VK_CLOSE_BRACKET:
      return "CLOSE_BRACKET";
    case KeyEvent.VK_ENTER:
      return "ENTER";
    case KeyEvent.VK_BACK_SPACE:
      return "BACK_SPACE";
    case KeyEvent.VK_TAB:
      return "TAB";
    case KeyEvent.VK_CANCEL:
      return "CANCEL";
    case KeyEvent.VK_CLEAR:
      return "CLEAR";
    case KeyEvent.VK_SHIFT:
      return "SHIFT";
    case KeyEvent.VK_CONTROL:
      return "CONTROL";
    case KeyEvent.VK_ALT:
      return "ALT";
    case KeyEvent.VK_PAUSE:
      return "PAUSE";
    case KeyEvent.VK_CAPS_LOCK:
      return "CAPS_LOCK";
    case KeyEvent.VK_ESCAPE:
      return "ESCAPE";
    case KeyEvent.VK_SPACE:
      return "SPACE";
    case KeyEvent.VK_PAGE_UP:
      return "PAGE_UP";
    case KeyEvent.VK_PAGE_DOWN:
      return "PAGE_DOWN";
    case KeyEvent.VK_END:
      return "END";
    case KeyEvent.VK_HOME:
      return "HOME";
    case KeyEvent.VK_LEFT:
      return "LEFT";
    case KeyEvent.VK_UP:
      return "UP";
    case KeyEvent.VK_RIGHT:
      return "RIGHT";
    case KeyEvent.VK_DOWN:
      return "DOWN";
    // numpad numeric keys handled below
    case KeyEvent.VK_MULTIPLY:
      return "MULTIPLY";
    case KeyEvent.VK_ADD:
      return "ADD";
    case KeyEvent.VK_SEPARATOR:
      return "SEPARATOR";
    case KeyEvent.VK_SUBTRACT:
      return "SUBTRACT";
    case KeyEvent.VK_DECIMAL:
      return "DECIMAL";
    case KeyEvent.VK_DIVIDE:
      return "DIVIDE";
    case KeyEvent.VK_DELETE:
      return "DELETE";
    case KeyEvent.VK_NUM_LOCK:
      return "NUM_LOCK";
    case KeyEvent.VK_SCROLL_LOCK:
      return "SCROLL_LOCK";
    case KeyEvent.VK_F1:
      return "F1";
    case KeyEvent.VK_F2:
      return "F2";
    case KeyEvent.VK_F3:
      return "F3";
    case KeyEvent.VK_F4:
      return "F4";
    case KeyEvent.VK_F5:
      return "F5";
    case KeyEvent.VK_F6:
      return "F6";
    case KeyEvent.VK_F7:
      return "F7";
    case KeyEvent.VK_F8:
      return "F8";
    case KeyEvent.VK_F9:
      return "F9";
    case KeyEvent.VK_F10:
      return "F10";
    case KeyEvent.VK_F11:
      return "F11";
    case KeyEvent.VK_F12:
      return "F12";
    case KeyEvent.VK_F13:
      return "F13";
    case KeyEvent.VK_F14:
      return "F14";
    case KeyEvent.VK_F15:
      return "F15";
    case KeyEvent.VK_F16:
      return "F16";
    case KeyEvent.VK_F17:
      return "F17";
    case KeyEvent.VK_F18:
      return "F18";
    case KeyEvent.VK_F19:
      return "F19";
    case KeyEvent.VK_F20:
      return "F20";
    case KeyEvent.VK_F21:
      return "F21";
    case KeyEvent.VK_F22:
      return "F22";
    case KeyEvent.VK_F23:
      return "F23";
    case KeyEvent.VK_F24:
      return "F24";
    case KeyEvent.VK_PRINTSCREEN:
      return "PRINTSCREEN";
    case KeyEvent.VK_INSERT:
      return "INSERT";
    case KeyEvent.VK_HELP:
      return "HELP";
    case KeyEvent.VK_META:
      return "META";
    case KeyEvent.VK_BACK_QUOTE:
      return "BACK_QUOTE";
    case KeyEvent.VK_QUOTE:
      return "QUOTE";
    case KeyEvent.VK_KP_UP:
      return "KP_UP";
    case KeyEvent.VK_KP_DOWN:
      return "KP_DOWN";
    case KeyEvent.VK_KP_LEFT:
      return "KP_LEFT";
    case KeyEvent.VK_KP_RIGHT:
      return "KP_RIGHT";
    case KeyEvent.VK_DEAD_GRAVE:
      return "DEAD_GRAVE";
    case KeyEvent.VK_DEAD_ACUTE:
      return "DEAD_ACUTE";
    case KeyEvent.VK_DEAD_CIRCUMFLEX:
      return "DEAD_CIRCUMFLEX";
    case KeyEvent.VK_DEAD_TILDE:
      return "DEAD_TILDE";
    case KeyEvent.VK_DEAD_MACRON:
      return "DEAD_MACRON";
    case KeyEvent.VK_DEAD_BREVE:
      return "DEAD_BREVE";
    case KeyEvent.VK_DEAD_ABOVEDOT:
      return "DEAD_ABOVEDOT";
    case KeyEvent.VK_DEAD_DIAERESIS:
      return "DEAD_DIAERESIS";
    case KeyEvent.VK_DEAD_ABOVERING:
      return "DEAD_ABOVERING";
    case KeyEvent.VK_DEAD_DOUBLEACUTE:
      return "DEAD_DOUBLEACUTE";
    case KeyEvent.VK_DEAD_CARON:
      return "DEAD_CARON";
    case KeyEvent.VK_DEAD_CEDILLA:
      return "DEAD_CEDILLA";
    case KeyEvent.VK_DEAD_OGONEK:
      return "DEAD_OGONEK";
    case KeyEvent.VK_DEAD_IOTA:
      return "DEAD_IOTA";
    case KeyEvent.VK_DEAD_VOICED_SOUND:
      return "DEAD_VOICED_SOUND";
    case KeyEvent.VK_DEAD_SEMIVOICED_SOUND:
      return "DEAD_SEMIVOICED_SOUND";
    case KeyEvent.VK_AMPERSAND:
      return "AMPERSAND";
    case KeyEvent.VK_ASTERISK:
      return "ASTERISK";
    case KeyEvent.VK_QUOTEDBL:
      return "QUOTEDBL";
    case KeyEvent.VK_LESS:
      return "LESS";
    case KeyEvent.VK_GREATER:
      return "GREATER";
    case KeyEvent.VK_BRACELEFT:
      return "BRACELEFT";
    case KeyEvent.VK_BRACERIGHT:
      return "BRACERIGHT";
    case KeyEvent.VK_AT:
      return "AT";
    case KeyEvent.VK_COLON:
      return "COLON";
    case KeyEvent.VK_CIRCUMFLEX:
      return "CIRCUMFLEX";
    case KeyEvent.VK_DOLLAR:
      return "DOLLAR";
    case KeyEvent.VK_EURO_SIGN:
      return "EURO_SIGN";
    case KeyEvent.VK_EXCLAMATION_MARK:
      return "EXCLAMATION_MARK";
    case KeyEvent.VK_INVERTED_EXCLAMATION_MARK:
      return "INVERTED_EXCLAMATION_MARK";
    case KeyEvent.VK_LEFT_PARENTHESIS:
      return "LEFT_PARENTHESIS";
    case KeyEvent.VK_NUMBER_SIGN:
      return "NUMBER_SIGN";
    case KeyEvent.VK_MINUS:
      return "MINUS";
    case KeyEvent.VK_PLUS:
      return "PLUS";
    case KeyEvent.VK_RIGHT_PARENTHESIS:
      return "RIGHT_PARENTHESIS";
    case KeyEvent.VK_UNDERSCORE:
      return "UNDERSCORE";
    case KeyEvent.VK_FINAL:
      return "FINAL";
    case KeyEvent.VK_CONVERT:
      return "CONVERT";
    case KeyEvent.VK_NONCONVERT:
      return "NONCONVERT";
    case KeyEvent.VK_ACCEPT:
      return "ACCEPT";
    case KeyEvent.VK_MODECHANGE:
      return "MODECHANGE";
    case KeyEvent.VK_KANA:
      return "KANA";
    case KeyEvent.VK_KANJI:
      return "KANJI";
    case KeyEvent.VK_ALPHANUMERIC:
      return "ALPHANUMERIC";
    case KeyEvent.VK_KATAKANA:
      return "KATAKANA";
    case KeyEvent.VK_HIRAGANA:
      return "HIRAGANA";
    case KeyEvent.VK_FULL_WIDTH:
      return "FULL_WIDTH";
    case KeyEvent.VK_HALF_WIDTH:
      return "HALF_WIDTH";
    case KeyEvent.VK_ROMAN_CHARACTERS:
      return "ROMAN_CHARACTERS";
    case KeyEvent.VK_ALL_CANDIDATES:
      return "ALL_CANDIDATES";
    case KeyEvent.VK_PREVIOUS_CANDIDATE:
      return "PREVIOUS_CANDIDATE";
    case KeyEvent.VK_CODE_INPUT:
      return "CODE_INPUT";
    case KeyEvent.VK_JAPANESE_KATAKANA:
      return "JAPANESE_KATAKANA";
    case KeyEvent.VK_JAPANESE_HIRAGANA:
      return "JAPANESE_HIRAGANA";
    case KeyEvent.VK_JAPANESE_ROMAN:
      return "JAPANESE_ROMAN";
    case KeyEvent.VK_KANA_LOCK:
      return "KANA_LOCK";
    case KeyEvent.VK_INPUT_METHOD_ON_OFF:
      return "INPUT_METHOD_ON_OFF";
    case KeyEvent.VK_AGAIN:
      return "AGAIN";
    case KeyEvent.VK_UNDO:
      return "UNDO";
    case KeyEvent.VK_COPY:
      return "COPY";
    case KeyEvent.VK_PASTE:
      return "PASTE";
    case KeyEvent.VK_CUT:
      return "CUT";
    case KeyEvent.VK_FIND:
      return "FIND";
    case KeyEvent.VK_PROPS:
      return "PROPS";
    case KeyEvent.VK_STOP:
      return "STOP";
    case KeyEvent.VK_COMPOSE:
      return "COMPOSE";
    case KeyEvent.VK_ALT_GRAPH:
      return "ALT_GRAPH";
    }
    if (keyCode >= KeyEvent.VK_NUMPAD0 && keyCode <= KeyEvent.VK_NUMPAD9) {
      char c = (char) (keyCode - KeyEvent.VK_NUMPAD0 + "0");
      return "NUMPAD" + c;
    }
    return "unknown(0x" + Integer.toString(keyCode, 16) + ")";
  }
}





Make the ENTER key act like the TAB key

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JTextField;
class MyTextField extends JTextField {
  MyTextField(int len) {
    super(len);
    addKeyListener(new KeyAdapter() {
      public void keyPressed(KeyEvent evt) {
        int key = evt.getKeyCode();
        if (key == KeyEvent.VK_ENTER)
          transferFocus();
      }
    });
  }
}





Overriding Many Default Typed Key Bindings in a JTextComponent

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
class MyKeyListener extends KeyAdapter {
  public void keyTyped(KeyEvent evt) {
    JTextComponent c = (JTextComponent) evt.getSource();
    char ch = evt.getKeyChar();
    if (Character.isLowerCase(ch) == false) {
      return;
    }
    try {
      c.getDocument().insertString(c.getCaretPosition(), "" + Character.toUpperCase(ch), null);
      evt.consume();
    } catch (BadLocationException e) {
    }
  }
}
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextField component = new JTextField();
    component.addKeyListener(new MyKeyListener());
    JFrame f = new JFrame();
    f.setSize(300, 300);
    f.setVisible(true);
  }
}





Setting Focus Traversal Keys in a Component

import java.awt.KeyboardFocusManager;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.KeyStroke;
public class Main {
  public static void main(String[] argv) throws Exception {
    JButton component = new JButton("a");
    Set set = new HashSet(component
        .getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
    set.add(KeyStroke.getKeyStroke("F2"));
    component.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set);
  }
}





The event IDs that the KeyEvent class defines

  1. KEY_TYPED
  2. KEY_PRESSED
  3. KEY_RELEASED


The KeyListener Interface

This interface defines methods to respond to events arising when a key on the keyboard is pressed or released.

Defined MethodsDescriptionkeyTyped(KeyEvent e)Called when a key on the keyboard is pressed and then releasedkeyPressed(KeyEvent e)Called when a key on the keyboard is pressedkeyReleased(KeyEvent e)Called when a key on the keyboard is released