Add document listener to a JTextField in Java

Description

The following code shows how to add document listener to a JTextField.

Example


import java.awt.FlowLayout;
//from   ww  w . java2 s . co  m
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class Main {
  public static void main(String[] argv) {
    JTextField tf = new JTextField(20);
    DocumentListener dl = new T1();
    tf.getDocument().addDocumentListener(dl);
    
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new FlowLayout());
    frame.add(tf);
    frame.setSize(300, 150);
    frame.setVisible(true);
  }
}

class T1 implements DocumentListener {
  public void changedUpdate(DocumentEvent e) {
  }

  public void insertUpdate(DocumentEvent e) {
    System.out.println(e);
  }

  public void removeUpdate(DocumentEvent e) {
    System.out.println(e);
  }
}

The code above generates the following result.

Add document listener to a JTextField in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer