Get document from DocumentListener : DocumentListener « Swing Event « Java Tutorial






import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class Test extends JFrame {
  JTextArea text = new JTextArea(10, 40);

  public Test() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    text.setLineWrap(true);

    text.getDocument().addDocumentListener(new DocumentListener() {
      public void showSize(DocumentEvent e) {
        System.out.println("Doc size: " + e.getDocument().getLength());
      }

      public void insertUpdate(DocumentEvent e) {
        showSize(e);
      }

      public void removeUpdate(DocumentEvent e) {
        showSize(e);
      }

      public void changedUpdate(DocumentEvent e) {
        showSize(e);
      }
    });

    getContentPane().add(
        new JScrollPane(text, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER), BorderLayout.CENTER);
    pack();
    setSize(200, 200);
  }

  public static void main(String[] args) {
    new Test().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