Handling Key Presses - Java Swing

Java examples for Swing:Key Event

Description

Handling Key Presses

Demo Code


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());
    }
  }
}

Related Tutorials