1. Technology

KeyListener

By

Definition:

The KeyListener interface is used to track the characters a user types into a text component. The interface is a simple one with only three methods that must be implemented by a class:

public interface KeyListener{

    public void keyPressed(KeyEvent e);
    public void keyReleased(KeyEvent e);
    public void keyTyped(KeyEvent e);

}

When a class implements the interface it can listen to key events:


inputText.addKeyListener(new KeyListener()
{
    @Override 
    public void keyPressed(KeyEvent e)
    {
       //when a key is pressed down then this method is called.
    }

    @Override
    public void keyReleased(KeyEvent e)
    {
       //when the key is released this method is called.
    }
              
    @Override
    public void keyTyped(KeyEvent e)
    {
       //In order for this method to be invoked the key combination 
       //must include a proper character. Modifying
       //(e.g., SHIFT, CTRL) or action (e.g., ENTER, DELETE) keys 
       //will not trigger this method by themselves.
    }
});

To find out more about the KeyListener interface and capturing key events have a look at Using a Key Listener and A KeyListener Example Program.

The KeyEvent object is passed to the KeyListener methods and contains information about the key event that occurs.

Glossary:

# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

  1. About.com
  2. Technology
  3. Java
  4. Java Glossary
  5. K
  6. Java Term: KeyListener

©2014 About.com. All rights reserved.