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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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
Thanks for your registration, follow us on our social networks to keep up-to-date