Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: AWT
Expertise: Beginner
Aug 10, 1999

Capturing KeyEvents

Question:
How can I capture KeyEvents in a Frame that doesn't have any TextFields or TextAreas?

Answer:
To enable a particular AWTEvent in a Component it suffices to add a listener for that event. When the first listener for a particular event type is registered, that event automatically becomes enabled for the component. So, all you have to do is add a KeyListener as in the following 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);
  }

}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap