JavaTM 2 Platform
Std. Ed. v1.3.1

javax.swing.text
Class AbstractDocument

java.lang.Object
  |
  +--javax.swing.text.AbstractDocument
All Implemented Interfaces:
Document, Serializable
Direct Known Subclasses:
DefaultStyledDocument, PlainDocument

public abstract class AbstractDocument
extends Object
implements Document, Serializable

An implementation of the document interface to serve as a basis for implementing various kinds of documents. At this level there is very little policy, so there is a corresponding increase in difficulty of use.

This class implements a locking mechanism for the document. It allows multiple readers or one writer, and writers must wait until all observers of the document have been notified of a previous change before beginning another mutation to the document. The read lock is aquired and released using the render method. A write lock is aquired by the methods that mutate the document, and are held for the duration of the method call. Notification is done on the thread that produced the mutation, and the thread has full read access to the document for the duration of the notification, but other readers are kept out until the notification has finished. The notification is a beans event notification which does not allow any further mutations until all listeners have been notified.

Any models subclassed from this class and used in conjunction with a text component that has a look and feel implementation that is derived from BasicTextUI may be safely updated asynchronously, because all access to the View hierarchy is serialized by BasicTextUI if the document is of type AbstractDocument. The locking assumes that an independant thread will access the View hierarchy only from the DocumentListener methods, and that there will be only one event thread active at a time.

If concurrency support is desired, there are the following additional implications. The code path for any DocumentListener implementation and any UndoListener implementation must be threadsafe, and not access the component lock if trying to be safe from deadlocks. The repaint and revalidate methods on JComponent are safe.

AbstractDocument models an implied break at the end of the document. Among other things this allows you to position the caret after the last character. As a result of this, getLength returns one less than the length of the Content. If you create your own Content, be sure and initialize it to have an additional character. Refer to StringContent and GapContent for examples of this. Another implication of this is that Elements that model the implied end character will have an endOffset == (getLength() + 1). For example, in DefaultStyledDocument getParagraphElement(getLength()).getEndOffset() == getLength() + 1 .

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. A future release of Swing will provide support for long term persistence.

See Also:
Serialized Form

Inner Class Summary
 class AbstractDocument.AbstractElement
          Implements the abstract part of an element.
static interface AbstractDocument.AttributeContext
          An interface that can be used to allow MutableAttributeSet implementations to use pluggable attribute compression techniques.
 class AbstractDocument.BranchElement
          Implements a composite element that contains other elements.
static interface AbstractDocument.Content
          Interface to describe a sequence of character content that can be edited.
 class AbstractDocument.DefaultDocumentEvent
          Stores document changes as the document is being modified.
static class AbstractDocument.ElementEdit
          An implementation of ElementChange that can be added to the document event.
 class AbstractDocument.LeafElement
          Implements an element that directly represents content of some kind.
 
Field Summary
protected static String BAD_LOCATION
          Error message to indicate a bad location.
static String BidiElementName
          Name of elements used to hold a unidirectional run
static String ContentElementName
          Name of elements used to represent content
static String ElementNameAttribute
          Name of the attribute used to specify element names.
protected  EventListenerList listenerList
          The event listener list for the document.
static String ParagraphElementName
          Name of elements used to represent paragraphs
static String SectionElementName
          Name of elements used to hold sections (lines/paragraphs).
 
Fields inherited from interface javax.swing.text.Document
StreamDescriptionProperty, TitleProperty
 
Constructor Summary
protected AbstractDocument(AbstractDocument.Content data)
          Constructs a new AbstractDocument, wrapped around some specified content storage mechanism.
protected AbstractDocument(AbstractDocument.Content data, AbstractDocument.AttributeContext context)
          Constructs a new AbstractDocument, wrapped around some specified content storage mechanism.
 
Method Summary
 void addDocumentListener(DocumentListener listener)
          Adds a document listener for notification of any changes.
 void addUndoableEditListener(UndoableEditListener listener)
          Adds an undo listener for notification of any changes.
protected  Element createBranchElement(Element parent, AttributeSet a)
          Creates a document branch element, that can contain other elements.
protected  Element createLeafElement(Element parent, AttributeSet a, int p0, int p1)
          Creates a document leaf element.
 Position createPosition(int offs)
          Returns a position that will track change as the document is altered.
 void dump(PrintStream out)
          Gives a diagnostic dump.
protected  void fireChangedUpdate(DocumentEvent e)
          Notifies all listeners that have registered interest for notification on this event type.
protected  void fireInsertUpdate(DocumentEvent e)
          Notifies all listeners that have registered interest for notification on this event type.
protected  void fireRemoveUpdate(DocumentEvent e)
          Notifies all listeners that have registered interest for notification on this event type.
protected  void fireUndoableEditUpdate(UndoableEditEvent e)
          Notifies all listeners that have registered interest for notification on this event type.
 int getAsynchronousLoadPriority()
          Get the asynchronous loading priority.
protected  AbstractDocument.AttributeContext getAttributeContext()
          Fetches the context for managing attributes.
 Element getBidiRootElement()
          Returns the root element of the bidirectional structure for this document.
protected  AbstractDocument.Content getContent()
          Gets the content for the document.
protected  Thread getCurrentWriter()
          Fetches the current writing thread if there is one.
abstract  Element getDefaultRootElement()
          Returns the root element that views should be based upon unless some other mechanism for assigning views to element structures is provided.
 Dictionary getDocumentProperties()
          Support for managing a set of properties.
 Position getEndPosition()
          Returns a position that represents the end of the document.
 int getLength()
          Returns the length of the data.
 EventListener[] getListeners(Class listenerType)
          Return an array of all the listeners of the given type that were added to this model.
abstract  Element getParagraphElement(int pos)
          Get the paragraph element containing the given position.
 Object getProperty(Object key)
          A convenience method for looking up a property value.
 Element[] getRootElements()
          Gets all root elements defined.
 Position getStartPosition()
          Returns a position that represents the start of the document.
 String getText(int offset, int length)
          Gets a sequence of text from the document.
 void getText(int offset, int length, Segment txt)
          Gets some text from the document potentially without making a copy.
 void insertString(int offs, String str, AttributeSet a)
          Inserts some content into the document.
protected  void insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr)
          Updates document structure as a result of text insertion.
protected  void postRemoveUpdate(AbstractDocument.DefaultDocumentEvent chng)
          Updates any document structure as a result of text removal.
 void putProperty(Object key, Object value)
          A convenience method for storing up a property value.
 void readLock()
          Acquires a lock to begin reading some state from the document.
 void readUnlock()
          Does a read unlock.
 void remove(int offs, int len)
          Removes some content from the document.
 void removeDocumentListener(DocumentListener listener)
          Removes a document listener.
 void removeUndoableEditListener(UndoableEditListener listener)
          Removes an undo listener.
protected  void removeUpdate(AbstractDocument.DefaultDocumentEvent chng)
          Updates any document structure as a result of text removal.
 void render(Runnable r)
          This allows the model to be safely rendered in the presence of currency, if the model supports being updated asynchronously.
 void setAsynchronousLoadPriority(int p)
          Set the asynchronous loading priority.
 void setDocumentProperties(Dictionary x)
          Replace the document properties dictionary for this document.
protected  void writeLock()
          Acquires a lock to begin mutating the document this lock protects.
protected  void writeUnlock()
          Releases the write lock held because the write operation is finished.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

listenerList

protected EventListenerList listenerList
The event listener list for the document.

BAD_LOCATION

protected static final String BAD_LOCATION
Error message to indicate a bad location.

ParagraphElementName

public static final String ParagraphElementName
Name of elements used to represent paragraphs

ContentElementName

public static final String ContentElementName
Name of elements used to represent content

SectionElementName

public static final String SectionElementName
Name of elements used to hold sections (lines/paragraphs).

BidiElementName

public static final String BidiElementName
Name of elements used to hold a unidirectional run

ElementNameAttribute

public static final String ElementNameAttribute
Name of the attribute used to specify element names.
Constructor Detail

AbstractDocument

protected AbstractDocument(AbstractDocument.Content data)
Constructs a new AbstractDocument, wrapped around some specified content storage mechanism.
Parameters:
data - the content

AbstractDocument

protected AbstractDocument(AbstractDocument.Content data,
                           AbstractDocument.AttributeContext context)
Constructs a new AbstractDocument, wrapped around some specified content storage mechanism.
Parameters:
data - the content
context - the attribute context
Method Detail

getDocumentProperties

public Dictionary getDocumentProperties()
Support for managing a set of properties. Callers can use the documentProperties dictionary to annotate the document with document-wide properties.
Returns:
a non null Dictionary
See Also:
setDocumentProperties(java.util.Dictionary)

setDocumentProperties

public void setDocumentProperties(Dictionary x)
Replace the document properties dictionary for this document.
Parameters:
x - the new dictionary
See Also:
getDocumentProperties()

fireInsertUpdate

protected void fireInsertUpdate(DocumentEvent e)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.
Parameters:
e - the event
See Also:
EventListenerList

fireChangedUpdate

protected void fireChangedUpdate(DocumentEvent e)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.
Parameters:
e - the event
See Also:
EventListenerList

fireRemoveUpdate

protected void fireRemoveUpdate(DocumentEvent e)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.
Parameters:
e - the event
See Also:
EventListenerList

fireUndoableEditUpdate

protected void fireUndoableEditUpdate(UndoableEditEvent e)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.
Parameters:
e - the event
See Also:
EventListenerList

getListeners

public EventListener[] getListeners(Class listenerType)
Return an array of all the listeners of the given type that were added to this model.
Since:
1.3

getAsynchronousLoadPriority

public int getAsynchronousLoadPriority()
Get the asynchronous loading priority. If less than zero, the document should not be loaded asynchronously.

setAsynchronousLoadPriority

public void setAsynchronousLoadPriority(int p)
Set the asynchronous loading priority.

render

public void render(Runnable r)
This allows the model to be safely rendered in the presence of currency, if the model supports being updated asynchronously. The given runnable will be executed in a way that allows it to safely read the model with no changes while the runnable is being executed. The runnable itself may not make any mutations.

This is implemented to aquire a read lock for the duration of the runnables execution. There may be multiple runnables executing at the same time, and all writers will be blocked while there are active rendering runnables. If the runnable throws an exception, its lock will be safely released. There is no protection against a runnable that never exits, which will effectively leave the document locked for it's lifetime.

If the given runnable attempts to make any mutations in this implementation, a deadlock will occur. There is no tracking of individual rendering threads to enable detecting this situation, but a subclass could incur the overhead of tracking them and throwing an error.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
render in interface Document
Parameters:
r - the renderer to execute.

getLength

public int getLength()
Returns the length of the data. This is the number of characters of content that represents the users data.
Specified by:
getLength in interface Document
Returns:
the length >= 0
See Also:
Document.getLength()

addDocumentListener

public void addDocumentListener(DocumentListener listener)
Adds a document listener for notification of any changes.
Specified by:
addDocumentListener in interface Document
Parameters:
listener - the listener
See Also:
Document.addDocumentListener(javax.swing.event.DocumentListener)

removeDocumentListener

public void removeDocumentListener(DocumentListener listener)
Removes a document listener.
Specified by:
removeDocumentListener in interface Document
Parameters:
listener - the listener
See Also:
Document.removeDocumentListener(javax.swing.event.DocumentListener)

addUndoableEditListener

public void addUndoableEditListener(UndoableEditListener listener)
Adds an undo listener for notification of any changes. Undo/Redo operations performed on the UndoableEdit will cause the appropriate DocumentEvent to be fired to keep the view(s) in sync with the model.
Specified by:
addUndoableEditListener in interface Document
Parameters:
listener - the listener
See Also:
Document.addUndoableEditListener(javax.swing.event.UndoableEditListener)

removeUndoableEditListener

public void removeUndoableEditListener(UndoableEditListener listener)
Removes an undo listener.
Specified by:
removeUndoableEditListener in interface Document
Parameters:
listener - the listener
See Also:
Document.removeDocumentListener(javax.swing.event.DocumentListener)

getProperty

public final Object getProperty(Object key)
A convenience method for looking up a property value. It is equivalent to:
 getDocumentProperties().get(key);
 
Specified by:
getProperty in interface Document
Parameters:
key - the non-null property key
Returns:
the value of this property or null
See Also:
getDocumentProperties()

putProperty

public final void putProperty(Object key,
                              Object value)
A convenience method for storing up a property value. It is equivalent to:
 getDocumentProperties().put(key, value);
 
If value is null this method will remove the property
Specified by:
putProperty in interface Document
Parameters:
key - the non-null key
value - the value
See Also:
getDocumentProperties()

remove

public void remove(int offs,
                   int len)
            throws BadLocationException
Removes some content from the document. Removing content causes a write lock to be held while the actual changes are taking place. Observers are notified of the change on the thread that called this method.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
remove in interface Document
Parameters:
offs - the starting offset >= 0
len - the number of characters to remove >= 0
Throws:
BadLocationException - the given remove position is not a valid position within the document
See Also:
Document.remove(int, int)

insertString

public void insertString(int offs,
                         String str,
                         AttributeSet a)
                  throws BadLocationException
Inserts some content into the document. Inserting content causes a write lock to be held while the actual changes are taking place, followed by notification to the observers on the thread that grabbed the write lock.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
insertString in interface Document
Parameters:
offs - the starting offset >= 0
str - the string to insert; does nothing with null/empty strings
a - the attributes for the inserted content
Throws:
BadLocationException - the given insert position is not a valid position within the document
See Also:
Document.insertString(int, java.lang.String, javax.swing.text.AttributeSet)

getText

public String getText(int offset,
                      int length)
               throws BadLocationException
Gets a sequence of text from the document.
Specified by:
getText in interface Document
Parameters:
offset - the starting offset >= 0
length - the number of characters to retrieve >= 0
Returns:
the text
Throws:
BadLocationException - the range given includes a position that is not a valid position within the document
See Also:
Document.getText(int, int)

getText

public void getText(int offset,
                    int length,
                    Segment txt)
             throws BadLocationException
Gets some text from the document potentially without making a copy. The character array returned in the given Segment should never be mutated. This kind of access to the characters of the document is provided to help make the rendering potentially more efficient. The caller should make no assumptions about the lifetime of the returned character array, which should be copied if needed beyond the use for rendering.
Specified by:
getText in interface Document
Parameters:
offset - the starting offset >= 0
length - the number of characters to retrieve >= 0
txt - the Segment object to retrieve the text into
Throws:
BadLocationException - the range given includes a position that is not a valid position within the document

createPosition

public Position createPosition(int offs)
                        throws BadLocationException
Returns a position that will track change as the document is altered.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
createPosition in interface Document
Parameters:
offs - the position in the model >= 0
Returns:
the position
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document
See Also:
Document.createPosition(int)

getStartPosition

public final Position getStartPosition()
Returns a position that represents the start of the document. The position returned can be counted on to track change and stay located at the beginning of the document.
Specified by:
getStartPosition in interface Document
Returns:
the position

getEndPosition

public final Position getEndPosition()
Returns a position that represents the end of the document. The position returned can be counted on to track change and stay located at the end of the document.
Specified by:
getEndPosition in interface Document
Returns:
the position

getRootElements

public Element[] getRootElements()
Gets all root elements defined. Typically, there will only be one so the default implementation is to return the default root element.
Specified by:
getRootElements in interface Document
Returns:
the root element

getDefaultRootElement

public abstract Element getDefaultRootElement()
Returns the root element that views should be based upon unless some other mechanism for assigning views to element structures is provided.
Specified by:
getDefaultRootElement in interface Document
Returns:
the root element
See Also:
Document.getDefaultRootElement()

getBidiRootElement

public Element getBidiRootElement()
Returns the root element of the bidirectional structure for this document. Its children represent character runs with a given Unicode bidi level.

getParagraphElement

public abstract Element getParagraphElement(int pos)
Get the paragraph element containing the given position. Sub-classes must define for themselves what exactly constitutes a paragraph. They should keep in mind however that a paragraph should at least be the unit of text over which to run the Unicode bidirectional algorithm.
Parameters:
pos - the starting offset >= 0
Returns:
the element

getAttributeContext

protected final AbstractDocument.AttributeContext getAttributeContext()
Fetches the context for managing attributes. This method effectively establishes the strategy used for compressing AttributeSet information.
Returns:
the context

insertUpdate

protected void insertUpdate(AbstractDocument.DefaultDocumentEvent chng,
                            AttributeSet attr)
Updates document structure as a result of text insertion. This will happen within a write lock. If a subclass of this class reimplements this method, it should delegate to the superclass as well.
Parameters:
chng - a description of the change
attr - the attributes for the change

removeUpdate

protected void removeUpdate(AbstractDocument.DefaultDocumentEvent chng)
Updates any document structure as a result of text removal. This method is called before the text is actually removed from the Content. This will happen within a write lock. If a subclass of this class reimplements this method, it should delegate to the superclass as well.
Parameters:
chng - a description of the change

postRemoveUpdate

protected void postRemoveUpdate(AbstractDocument.DefaultDocumentEvent chng)
Updates any document structure as a result of text removal. This method is called after the text has been removed from the Content. This will happen within a write lock. If a subclass of this class reimplements this method, it should delegate to the superclass as well.
Parameters:
chng - a description of the change

dump

public void dump(PrintStream out)
Gives a diagnostic dump.
Parameters:
out - the output stream

getContent

protected final AbstractDocument.Content getContent()
Gets the content for the document.
Returns:
the content

createLeafElement

protected Element createLeafElement(Element parent,
                                    AttributeSet a,
                                    int p0,
                                    int p1)
Creates a document leaf element. Hook through which elements are created to represent the document structure. Because this implementation keeps structure and content seperate, elements grow automatically when content is extended so splits of existing elements follow. The document itself gets to decide how to generate elements to give flexibility in the type of elements used.
Parameters:
parent - the parent element
a - the attributes for the element
p0 - the beginning of the range >= 0
p1 - the end of the range >= p0
Returns:
the new element

createBranchElement

protected Element createBranchElement(Element parent,
                                      AttributeSet a)
Creates a document branch element, that can contain other elements.
Parameters:
parent - the parent element
a - the attributes
Returns:
the element

getCurrentWriter

protected final Thread getCurrentWriter()
Fetches the current writing thread if there is one. This can be used to distinguish whether a method is being called as part of an existing modification or if a lock needs to be acquired and a new transaction started.

writeLock

protected final void writeLock()
Acquires a lock to begin mutating the document this lock protects. There can be no writing, notification of changes, or reading going on in order to gain the lock.
Throws:
IllegalStateException - thrown on illegal lock attempt. If the document is implemented properly, this can only happen if a document listener attempts to mutate the document. This situation violates the bean event model where order of delivery is not guaranteed and all listeners should be notified before further mutations are allowed.

writeUnlock

protected final void writeUnlock()
Releases the write lock held because the write operation is finished. This allows either a new writer or readers to aquire a lock.

readLock

public final void readLock()
Acquires a lock to begin reading some state from the document. There can be multiple readers at the same time. Writing blocks the readers until notification of the change to the listeners has been completed. This method should be used very carefully to avoid unintended compromise of the document. It should always be balanced with a readUnlock.
See Also:
readUnlock()

readUnlock

public final void readUnlock()
Does a read unlock. This signals that one of the readers is done. If there are no more readers then writing can begin again. This should be balanced with a readLock, and should occur in a finally statement so that the balance is guaranteed. The following is an example.

     readLock();
     try {
         // do something
     } finally {
         readUnlock();
     }
 
See Also:
readLock()

JavaTM 2 Platform
Std. Ed. v1.3.1

Submit a bug or feature
For further API reference and developer documentation, see Java 2 SDK SE Developer Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.

Java, Java 2D, and JDBC are trademarks or registered trademarks of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2001 Sun Microsystems, Inc. 901 San Antonio Road
Palo Alto, California, 94303, U.S.A. All Rights Reserved.



Spec-Zone.ru - all specs in one place



free hit counter