Check the DocumentEvent in DocumentListener for JTextField in Java

Description

The following code shows how to check the DocumentEvent in DocumentListener for JTextField.

Example


import java.awt.FlowLayout;
/*from   w  ww  . j  a va2 s.co  m*/
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

public class Main {
  public static void main(String[] args) {
    JFrame f = new JFrame("Text Field Elements");

    f.setLayout(new FlowLayout());


    JTextField textfield = new JTextField(10);
    textfield.getDocument().addDocumentListener(new MyDocListener());

    f.add(textfield);
    f.pack();
    f.setVisible(true);

  }


}

class MyDocListener implements DocumentListener {
  public void changedUpdate(DocumentEvent documentEvent) {
    printIt(documentEvent);
  }

  public void insertUpdate(DocumentEvent documentEvent) {
    printIt(documentEvent);
  }

  public void removeUpdate(DocumentEvent documentEvent) {
    printIt(documentEvent);
  }

  private void printIt(DocumentEvent documentEvent) {
    DocumentEvent.EventType type = documentEvent.getType();
    String typeString = null;
    if (type.equals(DocumentEvent.EventType.CHANGE)) {
      typeString = "Change";
    } else if (type.equals(DocumentEvent.EventType.INSERT)) {
      typeString = "Insert";
    } else if (type.equals(DocumentEvent.EventType.REMOVE)) {
      typeString = "Remove";
    }
    System.out.print("Type  :   " + typeString + " / ");
    Document source = documentEvent.getDocument();
    int length = source.getLength();
    try {
      System.out
          .println("Contents: " + source.getText(0, length));
    } catch (BadLocationException badLocationException) {
      System.out.println("Contents: Unknown");
    }
  }
};

The code above generates the following result.

Check the DocumentEvent in DocumentListener for 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