Java examples for Swing:Key Event
Handling Key Presses
import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JButton; public class Main { public static void main(String[] args) throws Exception { JButton component = new JButton(); component.addKeyListener(new MyKeyListener()); }// w w w .j av a 2 s . co m } class MyKeyListener extends KeyAdapter { public void keyPressed(KeyEvent evt) { // Check for key characters. if (evt.getKeyChar() == 'a') { System.out.println(evt.getKeyChar()); } // Check for key codes. if (evt.getKeyCode() == KeyEvent.VK_HOME) { System.out.println(evt.getKeyCode()); } } }