Using the JFC/Swing Packages |
A Swing text component uses a
Note: This section assumes that you're familiar with the AWT event listener scheme. If you aren't, you can read about it in The 1.1 AWT Event Model.
Document
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
TheDocumentListener
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
-- aPlainDocument
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:
- The document listener described in Listening for Changes on a Document updates a change log every time text in the listened to document changes.
- The document listener described in Using a Document Listener on a Text Field updates a numeric value based on several other values entered into text fields by the user.
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 theDocumentEvent
interface. Typically, the object passed into this method will be an instance ofDefaultDocumentEvent
which is defined inAbstractDocument
.To get the document that generated the event, you can use
DocumentEvent
'sgetDocument
method. Note thatDocumentEvent
does not inherit fromEventObject
like the other event classes. Thus it does not inherit thegetSource
method.In addition to
getDocument
, theDocumentEvent
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
is an interface defined within theDocumentEvent
interface.EventType getType()
- Returns the type of change that occurred.
ElementType
is a class defined within theDocumentEvent
interface that enumerates the possible changes that can occur on a document: insert text, remove text, and change text style.
Using the JFC/Swing Packages |