Java DocumentListener handle text component document event

Description

Java DocumentListener handle text component document event


import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

class MyPanel extends JPanel {
  public MyPanel() {
    setLayout(new BorderLayout());

    JTextField searchFld = new JTextField();
    searchFld.getDocument().addDocumentListener(new MyDocumentListener());
    add(searchFld, BorderLayout.NORTH);
  }//from w ww .ja  va  2  s .  c  om
}

class MyDocumentListener implements DocumentListener {
  public void insertUpdate(DocumentEvent e) {
    System.out.println(e);
  }
  public void removeUpdate(DocumentEvent e) {
    System.out.println(e);
  }

  public void changedUpdate(DocumentEvent e) {
    System.out.println("change: " + e);
  }
}

public class Main {

  public static void main(String[] args) {
    final JPanel c = new MyPanel();
    c.setPreferredSize(new Dimension(379, 200));
    JFrame frame = new JFrame("java2s.com");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.add(c);

    frame.setSize(300, 250);
    frame.setVisible(true);

  }
}



PreviousNext

Related