Java Swing Tutorials - Herong's Tutorial Examples - v4.32, by Herong Yang
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 listener.
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) 1997-2024 HerongYang.com. All Rights Reserved.
*/
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:
The text field should look like this:
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:
Table of Contents
Introduction of Java Swing Package
Graphics Environment of the Local System
JCheckBox - Swing Check Box Class
JRadioButton - Swing Radio Button Class
►JTextField - Swing Text Field Class
javax.swing.JTextField and Related Classes
►ActionListener and DocumentListener
JComboBox - Swing Combo Box Class
Menu Bar, Menus, Menu Items and Listeners
Creating Internal Frames inside the Main Frame
Layout of Components in a Container
JEditorPane - The Editor Pane Class
SwingWorker - The Background Task Worker
AWT (Abstract Windows Toolkit)