添加DocumentListener
的兩種方法應該完全相同。以下示例列出了全部類型爲DocumentListener.class
的收聽者。顯而易見的是DocumentListeners
本身,而anonymous inner class具有(實施相關)名稱DocumentListeners$1
。兩者都實現DocumentListener
接口。其他人是典型文本組件維護的一部分。請注意,顯示兩個副本,每個偵聽器添加一個副本。
控制檯:
[email protected]8ea
[email protected]
DocumentListeners[,0,0,128x38,layout=java.awt.FlowLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]
[email protected]
[email protected]
[email protected]8ea
[email protected]
DocumentListeners[,0,0,128x38,layout=java.awt.FlowLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]
[email protected]
[email protected]
代碼:
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();
}
});
}
}