Java AWT KeyEvent get key location

Description

Java AWT KeyEvent get key location

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 frame = new JFrame("Window Title");

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

      JTextField typingArea = new JTextField(20);
      typingArea.addKeyListener(new KeyListener() {
         public void keyTyped(KeyEvent e) {
            displayInfo(e, "KEY TYPED: ");
         }/*from  www.j a  v  a2 s . c om*/
         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 location = e.getKeyLocation();
            if (location == KeyEvent.KEY_LOCATION_STANDARD) {
               System.out.println("key location: standard");
            } else if (location == KeyEvent.KEY_LOCATION_LEFT) {
               System.out.println("key location: left");
            } else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
               System.out.println("key location: right");
            } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
               System.out.println("key location: numpad");
            } else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
               System.out.println("key location: unknown");
            }    
         }
      });
      frame.add(typingArea);
      frame.setVisible(true);
   }
}



PreviousNext

Related