AWT TextField and ActionListener

This section provides a tutorial example on how to create an AWT text field with an event handler implemented as the ActionListener listener.

AWT TextField component can trigger ActionEvent directly. Here is a sample program to show you how TextField ActionEvent works:

/* TextFieldTest.java
 * Copyright (c) 1997 HerongYang.com, All Rights Reserved.
 */
import java.awt.Frame;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TextFieldTest {
   public static void main(String[] a) {
      Frame f = new Frame("Text Field Test");
      MyTextField t = new MyTextField(16);
      f.add(t);
      f.pack();
      f.setVisible(true);
   }
   private static class MyTextField extends TextField 
      implements ActionListener {
      static int count = 0;
      public MyTextField(int l) {
         super(l);
         addActionListener(this);
      }
      public void actionPerformed(ActionEvent e) {
         count++;
         System.out.println(count+": Action performed - "+getText());
      }
   }
}

Run this program and do the following in the text field:

The text field should look like this:

AWT TextField ActionListener
AWT TextField ActionListener

And you should get the following output in the console window:

1: Action performed - Hello
2: Action performed - Hello World!

The output confirms that:

Last update: 1997.

Table of Contents

 About This Book

 JDK (Java Development Kit)

 Introduction of Java Swing Package

 Graphics Environment of the Local System

 JFrame - Main Frame Class

 JLabel - Swing Label Class

 JButton - Swing Button Class

 JRadioButton - Swing Radio Button Class

 JTextField - Swing Text Field Class

 Menu Bar, Menus, Menu Items and Listeners

 Creating Internal Frames inside the Main Frame

 Layout of Components in a Container

 LookAndFeel and UIManager

 Option Dialog Boxes

 JEditorPane - The Editor Pane Class

 SwingWorker - The Background Task Worker

AWT (Abstract Windows Toolkit)

 What Is AWT (Abstract Windows Toolkit)

 HelloAWT.java - My First AWT Program

 Closing AWT Frame and Terminating Application

 Drawing Graphics - Using paint() on Frame or Component

 Creating Labels with java.awt.Label Class

 Creating Buttons with java.awt.Button Class

 AWT Button Action Handler at the Component Level

 AWT Button Action Handler at the Frame Level

 AWT Button Mouse Click Handler at the Frame Level

AWT TextField and ActionListener

 MenuBarTest.java - AWT Menu Bar Test Program

 MenuTest.java - AWT Menu Test Program

 MenuItemTest.java - AWT Menu Item Test Program

 MenuItemActionListenerTest.java - AWT Menu Item Action Listener

 References

 Full Version in PDF/EPUB