How to Write a Document Listener : DocumentListener « Swing Event « Java Tutorial






How to Write a Document Listener
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;


class MyDocumentListener implements DocumentListener {
  final String newline = "\n";

  public void insertUpdate(DocumentEvent e) {
      updateLog(e, "inserted into");
  }
  public void removeUpdate(DocumentEvent e) {
      updateLog(e, "removed from");
  }
  public void changedUpdate(DocumentEvent e) {
      //Plain text components don't fire these events.
  }

  public void updateLog(DocumentEvent e, String action) {
      Document doc = (Document)e.getDocument();
      int changeLength = e.getLength();
      System.out.println(
          changeLength + " character"
        + ((changeLength == 1) ? " " : "s ")
        + action + " " + doc.getProperty("name") + "."
        + newline
        + "  Text length = " + doc.getLength() + newline);
  }
}


public class UsingDocumentListener {

  public static void main(String[] a){
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextField textField = new JTextField();
    
    textField.getDocument().addDocumentListener(new MyDocumentListener());
    textField.getDocument().putProperty("name", "Text Field");

    frame.add(textField);

    frame.setSize(300, 200);
    frame.setVisible(true);
  }


}








15.13.DocumentListener
15.13.1.How to Write a Document ListenerHow to Write a Document Listener
15.13.2.Get document from DocumentListener
15.13.3.Listening to JTextField Events with a DocumentListenerListening to JTextField Events with a DocumentListener
15.13.4.DocumentListener and DocumentEvent