Java AWT KeyEvent identify key code in key event handler

Introduction

To identify the keys, use their virtual key codes.

// Demonstrate the key event handlers.
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

class SimpleKey extends JTextArea implements KeyListener {

  public SimpleKey() {
    addKeyListener(this);
  }//from  www  .ja  v  a2 s  . c om

  public void keyPressed(KeyEvent ke) {
    System.out.println("Key Down ") ;
    int key = ke.getKeyCode();  
    switch(key) {  
      case KeyEvent.VK_F1:  
        System.out.println("<F1>");  
        break;  
      case KeyEvent.VK_F2:  
        System.out.println("<F2>");  
        break;  
      case KeyEvent.VK_F3:  
        System.out.println("<F3>");  
        break;  
      case KeyEvent.VK_PAGE_DOWN:  
        System.out.println("<PgDn>");  
        break;  
      case KeyEvent.VK_PAGE_UP:  
        System.out.println("<PgUp>");  
        break;  
      case KeyEvent.VK_LEFT:  
        System.out.println("<Left Arrow>");  
        break;  
      case KeyEvent.VK_RIGHT:  
        System.out.println("<Right Arrow>");  
        break;  
    }  
  }

  public void keyReleased(KeyEvent ke) {
    System.out.println("Key Up ") ;
  }

  public void keyTyped(KeyEvent ke) {
    System.out.println(ke.getKeyChar()) ;
  }

}

public class Main {
  public static void main(String args[]) {
    // Create the frame on the event dispatching thread.
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        // Create a new JFrame container.
        JFrame jfrm = new JFrame("java2s.com");

        // Give the frame an initial size.
        jfrm.setSize(220, 200);

        // Terminate the program when the user closes the application.
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // Add the label to the content pane.
        jfrm.add(new JScrollPane(new SimpleKey()));

        // Display the frame.
        jfrm.setVisible(true);

      }
    });
  }
}



PreviousNext

Related