Capturing KeyEvents

Capturing KeyEvents

How can I capture KeyEvents in a Frame that doesn’thave any TextFields or TextAreas?

To enable a particular AWTEvent in a Component it suffices to add alistener for that event. When the first listener for a particularevent type is registered, that event automatically becomes enabled forthe component. So, all you have to do is add a KeyListener as in thefollowing example:

import java.awt.*;import java.awt.event.*;public class KeyDemo {  public static void main(String[] args) {    Frame frame = new Frame("foo");    WindowListener exitListener;    exitListener = new WindowAdapter() {      public void windowClosing(WindowEvent e) {        Window window = e.getWindow();        window.setVisible(false);        window.dispose();        System.exit(0);      }    };    frame.addWindowListener(exitListener);    frame.addKeyListener( new KeyListener() {	public void keyPressed(KeyEvent e) {	  System.out.println("keyPressed: " + e.toString());	}	public void keyReleased(KeyEvent e) {	  System.out.println("keyReleased: " + e.toString());	}	public void keyTyped(KeyEvent e) {	  System.out.println("keyTyped: " + e.toString());	}      });          frame.setSize(400, 400);    frame.setVisible(true);  }}


Share the Post: