Java AWT KeyEvent compare to predefined key code

Description

Java AWT KeyEvent compare to predefined key code

import java.awt.BorderLayout;
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, BorderLayout.NORTH);
      f.setSize(300, 300);//from  w ww  . jav a2 s  .  c  o  m
      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());
      }
   }
}



PreviousNext

Related