Using KeyListener for AWT TextField

The following illustrates using KeyListener for AWT TextField. A KeyListener listens to key events such as key pressed, released and typed.

import java.awt.*;
import java.awt.event.*;
class TextFieldKeyEvent extends Frame implements KeyListener
{
TextField t;

    public TextFieldKeyEvent()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("KeyListener for TextField");
        setLayout(new FlowLayout());
       
        // Create textfield that shows upto 20 chars
        t=new TextField(20);
       
        // This object is object of KeyListener since
        // it implements KeyListener
        t.addKeyListener(this);
       
        add(t);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public void keyPressed(KeyEvent ke)
    {
        // Set title to both key character and its ascii code
        setTitle("You pressed "+ke.getKeyChar()+" ["+ke.getKeyCode()+"]");
    }
   
    public void keyReleased(KeyEvent ke)
    {
        setTitle("You released "+ke.getKeyChar()+" ["+ke.getKeyCode()+"]");
    }
   
    public void keyTyped(KeyEvent ke)
    {
        setTitle("You typed "+ke.getKeyChar()+" ["+ke.getKeyCode()+"]");
    }
   
    public static void main(String args[])
    {
        new TextFieldKeyEvent();
    }
}

When you start typing text, the keyTyped() is executed only when the key is a type-able i.e. the key is any character (number or letter or special char) but not other keys like Shift,Caps Lock, Ctrl and so on. However, any key can be pressed and released. keyTyped() doesn't need to involve a key press and a release. keyTyped() is executed even if you didn't release the key. A key is typed means that it is visible where you have typed.

getKeyCode(): This method gets the ascii code of the key.
getKeyChar(): This method returns the key character. For keys like Ctrl,Shift and so on, a ? is returned.

Using KeyListener for AWT TextField

Next: Using TextListener for AWT TextField
Previous: Using Shortcut for AWT MenuItem

No comments: