The two approaches to adding a DocumentListener
should be effectively identical. The example below lists all the listeners of type DocumentListener.class
for each event. The obvious one is DocumentListeners
itself, while the anonymous inner class has the (implementation dependent) name DocumentListeners$1
. Both implement the DocumentListener
interface. The others are part of typical text component maintenance. Note that two copies are shown, one from each listener added.
Console:
javax.swing.text.JTextComponent$InputMethodRequestsHandler@5090d8ea
DocumentListeners$1@559113f8
DocumentListeners[,0,0,128x38,layout=java.awt.FlowLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]
javax.swing.plaf.basic.BasicTextUI$UpdateHandler@27b62aab
javax.swing.text.DefaultCaret$Handler@28ab54eb
javax.swing.text.JTextComponent$InputMethodRequestsHandler@5090d8ea
DocumentListeners$1@559113f8
DocumentListeners[,0,0,128x38,layout=java.awt.FlowLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]
javax.swing.plaf.basic.BasicTextUI$UpdateHandler@27b62aab
javax.swing.text.DefaultCaret$Handler@28ab54eb
Code:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AbstractDocument;
/** @see http://stackoverflow.com/questions/8283067 */
public class DocumentListeners extends JPanel implements DocumentListener {
JTextField jtf = new JTextField("StackOverflow!");
public DocumentListeners() {
this.add(jtf);
jtf.getDocument().addDocumentListener(this);
jtf.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
print(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
print(e);
}
@Override
public void changedUpdate(DocumentEvent e) {
print(e);
}
});
}
private void print(DocumentEvent e) {
AbstractDocument ad = (AbstractDocument) jtf.getDocument();
for (DocumentListener dl : ad.getListeners(DocumentListener.class)) {
System.out.println(dl);
}
}
@Override
public void insertUpdate(DocumentEvent e) {
print(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
print(e);
}
@Override
public void changedUpdate(DocumentEvent e) {
print(e);
}
private void display() {
JFrame f = new JFrame("DocumentListeners");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new DocumentListeners().display();
}
});
}
}