|
|
< Day Day Up > |
|
How to Write a Document ListenerA Swing text component uses a Document[7] to hold and edit its text. Document events occur when the content of a document changes in any way. You attach a document listener to a text component's document rather than to the text component itself. For more information, see Implementing a Document Filter (page 72) in Chapter 3.
Figure 4 demonstrates document events on two plain text components. Figure 4. The DocumentEventDemo application.
Try This:
You can find the demo's code in DocumentEventDemo.java. Here's the demo's document event-handling code:
public class DocumentEventDemo ... {
...//where initialization occurs:
textField = new JTextField(20);
textField.addActionListener(new MyTextActionListener());
textField.getDocument().addDocumentListener(
new MyDocumentListener());
textField.getDocument().putProperty("name", "Text Field");
textArea = new JTextArea();
textArea.getDocument().addDocumentListener(
new MyDocumentListener());
textArea.getDocument().putProperty("name", "Text Area");
...
class MyDocumentListener implements DocumentListener {
String newline = "\n";
public void insertUpdate(DocumentEvent e) {
updateLog(e, "inserted into");
}
public void removeUpdate(DocumentEvent e) {
updateLog(e, "removed from");
}
public void changedUpdate(DocumentEvent e) {
//Plain text components don't fire these events
}
public void updateLog(DocumentEvent e, String action) {
Document doc = (Document)e.getDocument();
int changeLength = e.getLength();
displayArea.append(
changeLength + " character" +
((changeLength == 1) ? " " : "s ") +
action + doc.getProperty("name") + "." + newline +
" Text length = " + doc.getLength() + newline);
}
}
Document listeners shouldn't modify the contents of the document. The change is already complete by the time the listener is notified of the change. Instead, write a custom document that overrides the insertString or remove methods, or both. See Listening for Changes on a Document (page 73) in Chapter 3 for details. The Document Listener APITables 9 and 10 list the methods in the DocumentListener and DocumentEvent interfaces. Also refer to the DocumentListener API documentation online at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/event/DocumentListener.html. The DocumentEvent API documentation is online at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/event/DocumentEvent.html.
Examples That Use Document ListenersThe following examples use document listeners.
|
|
|
< Day Day Up > |
|