Listening for Editing Changes in a JTextComponent - Java Swing

Java examples for Swing:JTextComponent

Description

Listening for Editing Changes in a JTextComponent

Demo Code

import javax.swing.JTextPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;

public class Main {
  public static void main(String[] argv) {
    JTextComponent textcomp = new JTextPane();
    textcomp.setText("Initial Text");
    textcomp.getDocument().addDocumentListener(new DocumentListener() {
      // This method is called after an insert into the document
      public void insertUpdate(DocumentEvent evt) {
        // Get index of newly inserted characters
        int off = evt.getOffset();

        // Get length of new inserted characters
        int len = evt.getLength();

        try {//from   w  ww .j av a  2  s.com
          // Get inserted string
          String str = evt.getDocument().getText(off, len);
        } catch (BadLocationException e) {
        }
      }

      // This method is called after a removal from the document
      public void removeUpdate(DocumentEvent evt) {
        // Get starting index of removed characters
        int off = evt.getOffset();

        // Get length of removed characters
        int len = evt.getLength();

        // The removed characters are not available
      }

      public void changedUpdate(DocumentEvent evt) {
        // Get starting index of characters whose attributes have changed
        int off = evt.getOffset();

        // Get length of characters whose attributes have changed
        int len = evt.getLength();
      }
    });
  }

}

Related Tutorials