Document: getText(int offset, int length) : Document « javax.swing.text « Java by API






Document: getText(int offset, int length)

 

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;

public class MainClass {
  public static void main(String args[]) throws Exception {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextField nameTextField = new JTextField();
    frame.add(nameTextField, BorderLayout.NORTH);
    frame.add(new JTextField(), BorderLayout.SOUTH);

    DocumentListener documentListener = new 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");
        }
      }
    };
    nameTextField.getDocument().addDocumentListener(documentListener);

    
    frame.setSize(250, 100);
    frame.setVisible(true);
  }
}

           
         
  








Related examples in the same category

1.Document: addDocumentListener(DocumentListener listener)
2.Document: addUndoableEditListener(UndoableEditListener listener)
3.Document: dump(PrintStream out)
4.Document: getDefaultRootElement()
5.Document: getLength()
6.Document: insertString(int offset, String str, AttributeSet a)
7.Document: remove(int offs, int len)