Using ActionListener for AWT TextField

The following illustrates use of ActionListener for AWT TextField.

import java.awt.*;
import java.awt.event.*;
class TextFieldAction extends Frame
{
TextField t;
    public TextFieldAction()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("TextField with ActionListener demo");
        setLayout(new FlowLayout());
       
        // Create simple TextField that shows 20 chars
        t=new TextField(20);
       
        // Add ActionListener
        t.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
                // Change frame title
                setTitle(t.getText());
            }
        });
       
        // Add the textfield
        add(t);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new TextFieldAction();
    }
}
TextFieldAction(): Code illustrating ActionListener on AWT TextField is written here.
new TextFieldAction(): Code that initializes the GUI is written here.

Just type the text and hit enter to change the title because ActionEvent is generated.
Using ActionListener for AWT TextField

No comments: