Handling Key Presses : KeyListener « Swing Event « Java Tutorial






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);
    f.setSize(300, 300);
    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());
    }
  }
}








15.21.KeyListener
15.21.1.The KeyListener Interface
15.21.2.The event IDs that the KeyEvent class defines
15.21.3.How to Write a Key Listener
15.21.4.Demonstrates key eventsDemonstrates key events
15.21.5.KeyListener and KeyEvent
15.21.6.Handling Key Presses
15.21.7.Get key pressed as a key character (which is a Unicode character)
15.21.8.Get key pressed as a key code
15.21.9.Setting Focus Traversal Keys in a Component
15.21.10.Listing the Key Bindings in a Component
15.21.11.Make the ENTER key act like the TAB key
15.21.12.Overriding Many Default Typed Key Bindings in a JTextComponent