|
|
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.
Documentto 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
TheDocumentListenerinterface 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-- aPlainDocumentdoes 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 theDocumentEventinterface. Typically, the object passed into this method will be an instance of
DefaultDocumentEventwhich is defined in
AbstractDocument.To get the document that generated the event, you can use
DocumentEvent'sgetDocumentmethod. Note thatDocumentEventdoes not inherit fromEventObjectlike the other event classes. Thus it does not inherit thegetSourcemethod.In addition to
getDocument, theDocumentEventclass 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.
ElementChangeis an interface defined within the
DocumentEventinterface.EventType getType()- Returns the type of change that occurred.
ElementTypeis a class defined within the
DocumentEventinterface that enumerates the possible changes that can occur on a document: insert text, remove text, and change text style.
|
|
Using the JFC/Swing Packages |