Java Swing Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 4.00

ActionListener and DocumentListener

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

As you can see from the previous section, a text field can trigger action events directly. It can also trigger document events indirectly through its associated document. Here is a sample program to show you how and when those events are triggered:

/**
 * JTextFieldTest.java
 * Copyright (c) 2002 by Dr. Herong Yang, http://www.herongyang.com/
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class JTextFieldTest {
   public static void main(String[] a) {
      JFrame f = new JFrame("Text Field Test");
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      MyTextField t = new MyTextField(16);
      f.getContentPane().add(t,BorderLayout.CENTER);
      f.pack();
      f.setVisible(true);
   }
   private static class MyTextField extends JTextField 
      implements ActionListener, DocumentListener  {
      static int count = 0;
      public MyTextField(int l) {
         super(l);
         addActionListener(this);
         Document doc = this.getDocument();
         System.out.println("The document object: "+doc);
         doc.addDocumentListener(this);
      }
      public void actionPerformed(ActionEvent e) {
         count++;
         System.out.println(count+": Action performed - "+getText());
      }
      public void insertUpdate(DocumentEvent e) {
         count++;
         System.out.println(count+": Insert update - "+getText());
      }
      public void removeUpdate(DocumentEvent e) {
         count++;
         System.out.println(count+": Remove update - "+getText());
      }
      public void changedUpdate(DocumentEvent e) {
         count++;
         System.out.println(count+": Change update - "+getText());
      }
   }
}

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

  • Type "h".
  • Type "i".
  • Press the backspace key to remove "i".
  • Type "e".
  • Press the enter key.

The text field should look like this:
JTextField Listeners

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

The document object: javax.swing.text.PlainDocument@4e79f1
1: Insert update - h
2: Insert update - hi
3: Remove update - h
4: Insert update - he
5: Action performed - he

The output confirms that:

  • TextField class is using PlainDocument as the default document type.
  • ActionListener is called when the enter key is pressed.
  • changeUpdate() is not called.

Sample programs listed in this section have been tested with JDK 1.3.1, 1.4.1, 1.5.0, and 1.6.0.

Last update: 2009.

Sections in This Chapter

javax.swing.JTextField and Related Classes

ActionListener and DocumentListener

Dr. Herong Yang, updated in 2009
ActionListener and DocumentListener