How to Write a Document Listener

 < Day Day Up > 

A 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.

[7] Document API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/Document.html.

Figure 4 demonstrates document events on two plain text components .

Figure 4. The DocumentEventDemo application.

graphics/10fig04.gif

Try This:

  1. graphics/cd_icon.gif

    Run DocumentEventDemo using Java Web Start or compile and run the example yourself. [8]

    [8] To run DocumentEventDemo using Java Web Start, click the DocumentEventDemo link on the RunExamples/events.html page on the CD. You can find the source files here: JavaTutorial/uiswing/events/example-1dot4/index.html#DocumentEventDemo .

  2. Type in the text field at the upper left of the window or the text area beneath the text field. One document event is fired for each character typed.

  3. Delete text with the backspace key. One document event is fired for each backspace key pressed.

  4. Select text and then delete it by pressing Backspace or by using a keyboard command such as CTRL-X (cut). One document event is fired for the entire deletion.

  5. Copy text from one text component into the other using keyboard commands such as CTRL-C (copy) and CTRL-V (paste). One document event is fired for the entire paste operation regardless of the length of the text pasted. If text is selected in the target text component before the paste command is issued, an additional document event is fired because the selected text is deleted first.

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 API

Tables 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.

Table 11. The DocumentListener Interface ( DocumentListener has no adapter class.)

Method

Purpose

changedUpdate(DocumentEvent)

Called when the style of some of the text in the listened-to document changes. This sort of event is fired only from a StyledDocument a PlainDocument does not fire these events.

insertUpdate(DocumentEvent)

Called when text is inserted into the listened-to document.

removeUpdate(DocumentEvent)

Called when text is removed from the listened-to document.

Table 12. The DocumentEvent Interface [a]

Method

Purpose

Document getDocument()

Return the document that fired the event. Note that the DocumentEvent interface does not inherit from EventObject . Therefore, it does not inherit the getSource method.

int getLength()

Return the length of the change.

int getOffset()

Return the location within the document of the first character changed.

ElementChange getChange(Element)

Return details about what elements in the document have changed and how. ElementChange is an interface defined within the DocumentEvent interface.

EventType getType()

Return the type of change that occurred. EventType is a class defined within the DocumentEvent interface that enumerates the possible changes that can occur on a document: insert text, remove text, and change text style.

[a] Each document event method is passed an object that implements the DocumentEvent interface. Typically, this is an instance of DefaultDocumentEvent , defined in AbstractDocument .

Examples That Use Document Listeners

The following examples use document listeners.

Example

Where Described

Notes

DocumentEventDemo

This section

Reports all document events that occur on the documents for both a text field and a text area. One listener listens to both text components and uses a client property on the document to determine which component fired the event.

TextComponentDemo

Listening for Changes on a Document (page 73)

Updates a change log every time text in the listened-to document changes.

ListDemo

How to Use Lists (page 267)

Has an event listener that implements both the DocumentListener and the ActionListener interfaces. As a document listener, it's used to disable a particular button when the text field is empty, and to enable the button when the text field contains characters .

 < Day Day Up > 


JFC Swing Tutorial, The. A Guide to Constructing GUIs
The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)
ISBN: 0201914670
EAN: 2147483647
Year: 2004
Pages: 171

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net