Document Events

When changes are made to a Document, observers of the Document are notified using the event types DocumentEvent and UndoableEditEvent, defined in the javax.swing.event package. UndoableEditEvent and its associated listener interface were discussed in Chapter 18.

In this section, we’ll look at DocumentEvent and several related classes, which make up a surprisingly complex[53] and powerful event model. We’ll also look at the DocumentListener interface used to receive notification of Document changes.

The DocumentEvent Interface

A DocumentEvent is fired to indicate that some change has been made to a Document. It contains information about the area within the Document that was modified, along with information about the details of the change.

Unlike most events, DocumentEvent is an interface rather than a class. This is done so that an undo-capable class (such as AbstractDocument) can create an event implementation that extends a class from the undo package and implements this interface. We’ll see all the details of how this works over the next few pages. If you’re curious, you can peek ahead to Figure 20.10 for a complete diagram of DocumentEvent and related classes.

A default implementation of this interface is provided by Abstract-Document.DefaultDocumentEvent.

Properties

Table 20.19 shows the properties defined by the DocumentEvent interface. The document property specifies the Document object whose change caused this event to be fired. Length and offset define the ...

Get Java Swing now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.