Using TextListener for AWT TextField

The following illustrates use of TextListener with AWT TextField. TextListener listens to TextEvent which is generated when the text in a text component (a TextField or TextArea) changes.

import java.awt.*;
import java.awt.event.*;
class TextFieldTextEvent extends Frame implements TextListener
{
TextField t;

    public TextFieldTextEvent()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("TextListener for TextField");
        setLayout(new FlowLayout());
       
        // Create textfield that shows upto 20 chars
        t=new TextField(20);
       
        // This object is object of TextListener since
        // it implements TextListener
        t.addTextListener(this);
       
        add(t);
       
        setSize(400,400);
        setVisible(true);
    }
   
    // Called whenever the text in a text component (here t) changes
    public void textValueChanged(TextEvent te)
    {
        // Update the frame title
        setTitle(t.getText());
    }
   
    public static void main(String args[])
    {
        new TextFieldTextEvent();
    }
}

The TextEvent class doesn't contain methods to get the text because you have them in the TextField class. This event is fired only when there is a change in the text (either deletion,addition). This is much similar to DocumentEvent in swing but unlike in DocumentListener, TextListener doesn't have separate methods (handlers) for insertion and deletion.

TextFieldTextEvent(): This contains code illustrating the use of TextListener with AWT TextField.
new TextFieldTextEvent(): This creates object for the class.

Using TextListener for AWT TextField

Next: Using MouseListener for AWT Frame
Previous: Using KeyListener for AWT TextField

No comments: