implements DocumentListener : DocumentListener « javax.swing.event « Java by API






implements DocumentListener

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