Demonstrating the KeyListener : Various Event Listener « Swing JFC « Java

Demonstrating the KeyListener

Demonstrating the KeyListener
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class KeyTest {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Key Listener");
    Container contentPane = frame.getContentPane();

    KeyListener listener = new KeyListener() {
      public void keyPressed(KeyEvent e) {
        dumpInfo("Pressed", e);

      public void keyReleased(KeyEvent e) {
        dumpInfo("Released", e);

      public void keyTyped(KeyEvent e) {
        dumpInfo("Typed", e);

      private void dumpInfo(String s, KeyEvent e) {
        int code = e.getKeyCode();
        System.out.println("\tCode: " + KeyEvent.getKeyText(code));
        System.out.println("\tChar: " + e.getKeyChar());
        int mods = e.getModifiersEx();
        System.out.println("\tMods: "
            + KeyEvent.getModifiersExText(mods));
        System.out.println("\tLocation: "
            + location(e.getKeyLocation()));
        System.out.println("\tAction? " + e.isActionKey());

      private String location(int location) {
        switch (location) {
        case KeyEvent.KEY_LOCATION_LEFT:
          return "Left";
        case KeyEvent.KEY_LOCATION_RIGHT:
          return "Right";
        case KeyEvent.KEY_LOCATION_NUMPAD:
          return "NumPad";
        case KeyEvent.KEY_LOCATION_STANDARD:
          return "Standard";
        case KeyEvent.KEY_LOCATION_UNKNOWN:
          return "Unknown";

    JTextField text = new JTextField();
    contentPane.add(text, BorderLayout.NORTH);

Related examples in the same category

1.Demonstrating the WindowListener with a WindowAdapterDemonstrating the WindowListener with a WindowAdapter
2.Demonstrating the ActionListenerDemonstrating the ActionListener
3.Demonstrating the AdjustmentListenerDemonstrating the AdjustmentListener
4.Demonstrating the AncestorListener
5.Demonstrating the ComponentListenerDemonstrating the ComponentListener
6.Demonstrating the ContainerListenerDemonstrating the ContainerListener
7.Demonstrating the FocusListenerDemonstrating the FocusListener
8.Demonstrating the HyperlinkListenerDemonstrating the HyperlinkListener
9.Demonstrating the InternalFrameListenerDemonstrating the InternalFrameListener
10.Demonstrating the ItemListenerDemonstrating the ItemListener
11.Demonstrating the MenuListenerDemonstrating the MenuListener
12.Demonstrating the MouseListener and MouseMotionListenerDemonstrating the MouseListener and MouseMotionListener
13.Demonstrating the MouseWheelListenerDemonstrating the MouseWheelListener
14.Demonstrating the PopupMenuListenerDemonstrating the PopupMenuListener
15.Demonstrating the WindowListener
16.Responding to KeystrokesResponding to Keystrokes