Monday, February 15, 2010

Java's KeyListener

Events are handled in Java through Event handlers and listeners. For every listener, there is a corresponding event handler. There are methods associated with this interface and shall be worked with even it means doing nothing.

Below is an application of key listener. 

[+/-] show/hide

/*responding to user input*/
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class KeyViewerGUI extends JFrame implements KeyListener {
JTextField keyText = new JTextField(80);
JLabel keyLabel = new JLabel("Press any key in the text field.");

KeyViewerGUI() {
setSize(350, 100);
BorderLayout bord = new BorderLayout();
add(keyLabel, BorderLayout.NORTH);
add(keyText, BorderLayout.CENTER);

public void keyTyped(KeyEvent input) {
char key = input.getKeyChar();
keyLabel.setText("You pressed " + key);

public void keyPressed(KeyEvent txt) {
// do nothing

public void keyReleased(KeyEvent txt) {
// do nothing

public static void main(String[] arguments) {
KeyViewerGUI frame = new KeyViewerGUI();

No comments: