Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Writing Event Listeners

How to Write a Document Listener

A Swing text component uses a Document(in the API reference documentation) 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.

Document Event Methods

The DocumentListener interface contains these three methods:
void changedUpdate(DocumentEvent)
Called when the style of some of the text in the listened-to document changes. This sort of event is generated only from a StyledDocument-- a PlainDocument does not generate these events.

void insertUpdate(DocumentEvent)
Called when text is inserted into the listened-to document.

void removeUpdate(DocumentEvent)
Called when text is removed from the listened-to document.

Examples of Handling Document Events

Two examples described in other sections have document listeners: Both of those sections made an important point that is worth repeating here:
Never modify the contents of document from within a document listener. Your program might deadlock. Instead, provide a custom document for your text component.

The DocumentEvent Interface

Each document event method has a single parameter: an instance of a class that implements the DocumentEvent(in the API reference documentation) interface. Typically, the object passed into this method will be an instance of DefaultDocumentEvent(in the API reference documentation) which is defined in AbstractDocument.

To get the document that generated the event, you can use DocumentEvent's getDocument method. Note that DocumentEvent does not inherit from EventObject like the other event classes. Thus it does not inherit the getSource method.

In addition to getDocument, the DocumentEvent class provides these handy methods:

int getLength()
Returns the length of the change.
int getOffset()
Returns the location within the document of the first character changed.
ElementChange getChange(Element)
Returns details about what elements in the document have changed and how. ElementChange(in the API reference documentation) is an interface defined within the DocumentEvent interface.
EventType getType()
Returns the type of change that occurred. EventType(in the API reference documentation) 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.


Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Writing Event Listeners