Java AWT KeyListener handle key event

Description

Java AWT KeyListener handle key event

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

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

public class Main {
   public static void main(String[] args) {
      JFrame aWindow = new JFrame("Window Title");

      aWindow.setBounds(50, 100, 300, 300);
      aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      JTextField typingArea = new JTextField(20);
      typingArea.addKeyListener(new KeyListener() {
         public void keyTyped(KeyEvent e) {
            displayInfo(e, "KEY TYPED: ");
         }//w  ww .  ja v a 2 s  .  com
         public void keyPressed(KeyEvent e) {
            displayInfo(e, "KEY PRESSED: ");
         }
         public void keyReleased(KeyEvent e) {
            displayInfo(e, "KEY RELEASED: ");
         }
         protected void displayInfo(KeyEvent e, String s) {
            int id = e.getID();
            if (id == KeyEvent.KEY_TYPED) {
               char c = e.getKeyChar();
               System.out.println("key character = '" + c + "'");
            } else {
               int keyCode = e.getKeyCode();
               System.out.println("key code = " + keyCode + " (" + KeyEvent.getKeyText(keyCode) + ")");
            }           
         }
      });
      aWindow.add(typingArea);
      aWindow.setVisible(true);
   }
}



PreviousNext

Related