DefaultStyledDocument (Java SE 26 & JDK 26)
Description: declaration: module: java.desktop, package: javax.swing.text, class: DefaultStyledDocument
Keywords: javax.swing.text.DefaultStyledDocument class

# Class DefaultStyledDocument

java.lang.Object
javax.swing.text.AbstractDocument
javax.swing.text.DefaultStyledDocument

All Implemented Interfaces:
  `Serializable, Document, StyledDocument`

Direct Known Subclasses:
  `HTMLDocument`

public class DefaultStyledDocument extends AbstractDocument implements StyledDocument
A document that can be marked up with character and paragraph styles in a manner similar to the Rich Text Format. The element structure for this document represents style crossings for style runs. These style runs are mapped into a paragraph element structure (which may reside in some other structure). The style runs break at paragraph boundaries since logical styles are assigned to paragraph boundaries.

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. As of 1.4, support for long term storage of all JavaBeans has been added to the `java.beans` package. Please see `XMLEncoder`.

See Also:
  - `Document`
  - `AbstractDocument`

- ## Nested Class Summary

  Nested Classes
  Modifier and Type
  Class
  Description
  `static class`
  `DefaultStyledDocument.AttributeUndoableEdit`
  An UndoableEdit used to remember AttributeSet changes to an Element.
  `class`
  `DefaultStyledDocument.ElementBuffer`
  Class to manage changes to the element hierarchy.
  `static class`
  `DefaultStyledDocument.ElementSpec`
  Specification for building elements.
  `protected class`
  `DefaultStyledDocument.SectionElement`
  Default root element for a document... maps out the paragraphs/lines contained.

  ### Nested classes/interfaces declared in class AbstractDocument

  `AbstractDocument.AbstractElement, AbstractDocument.AttributeContext, AbstractDocument.BranchElement, AbstractDocument.Content, AbstractDocument.DefaultDocumentEvent, AbstractDocument.ElementEdit, AbstractDocument.LeafElement`
  Modifier and Type
  Class
  Description
  `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

  Fields
  Modifier and Type
  Field
  Description
  `protected DefaultStyledDocument.ElementBuffer`
  `buffer`
  The element buffer.
  `static final int`
  `BUFFER_SIZE_DEFAULT`
  The default size of the initial content buffer.

  ### Fields declared in class AbstractDocument

  `BAD_LOCATION, BidiElementName, ContentElementName, ElementNameAttribute, listenerList, ParagraphElementName, SectionElementName`
  Modifier and Type
  Field
  Description
  `protected static final String`
  `BAD_LOCATION`
  Error message to indicate a bad location.
  `static final String`
  `BidiElementName`
  Name of elements used to hold a unidirectional run
  `static final String`
  `ContentElementName`
  Name of elements used to represent content
  `static final String`
  `ElementNameAttribute`
  Name of the attribute used to specify element names.
  `protected EventListenerList`
  `listenerList`
  The event listener list for the document.
  `static final String`
  `ParagraphElementName`
  Name of elements used to represent paragraphs
  `static final String`
  `SectionElementName`
  Name of elements used to hold sections (lines/paragraphs).

  ### Fields declared in interface Document

  `StreamDescriptionProperty, TitleProperty`
  Modifier and Type
  Field
  Description
  `static final String`
  `StreamDescriptionProperty`
  The property name for the description of the stream used to initialize the document.
  `static final String`
  `TitleProperty`
  The property name for the title of the document, if there is one.

- ## Constructor Summary

  Constructors
  Constructor
  Description
  `DefaultStyledDocument()`
  Constructs a default styled document.
  `DefaultStyledDocument(AbstractDocument.Content c, StyleContext styles)`
  Constructs a styled document.
  `DefaultStyledDocument(StyleContext styles)`
  Constructs a styled document with the default content storage implementation and a shared set of styles.

- ## Method Summary

  Modifier and Type
  Method
  Description
  `void`
  `addDocumentListener(DocumentListener listener)`
  Adds a document listener for notification of any changes.
  `Style`
  `addStyle(String nm, Style parent)`
  Adds a new style into the logical style hierarchy.
  `protected void`
  `create(DefaultStyledDocument.ElementSpec[] data)`
  Initialize the document to reflect the given element structure (i.e. the structure reported by the `getDefaultRootElement` method.
  `protected AbstractDocument.AbstractElement`
  `createDefaultRoot()`
  Creates the root element to be used to represent the default document structure.
  `Color`
  `getBackground(AttributeSet attr)`
  Gets the background color from an attribute set.
  `Element`
  `getCharacterElement(int pos)`
  Gets a character element based on a position.
  `Element`
  `getDefaultRootElement()`
  Gets the default root element.
  `Font`
  `getFont(AttributeSet attr)`
  Gets the font from an attribute set.
  `Color`
  `getForeground(AttributeSet attr)`
  Gets the foreground color from an attribute set.
  `Style`
  `getLogicalStyle(int p)`
  Fetches the logical style assigned to the paragraph represented by the given position.
  `Element`
  `getParagraphElement(int pos)`
  Gets the paragraph element at the offset `pos`.
  `Style`
  `getStyle(String nm)`
  Fetches a named style previously added.
  `Enumeration<?>`
  `getStyleNames()`
  Fetches the list of style names.
  `protected void`
  `insert(int offset, DefaultStyledDocument.ElementSpec[] data)`
  Inserts new elements in bulk.
  `protected void`
  `insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr)`
  Updates document structure as a result of text insertion.
  `void`
  `removeDocumentListener(DocumentListener listener)`
  Removes a document listener.
  `void`
  `removeElement(Element elem)`
  Removes an element from this document.
  `void`
  `removeStyle(String nm)`
  Removes a named style previously added to the document.
  `protected void`
  `removeUpdate(AbstractDocument.DefaultDocumentEvent chng)`
  Updates document structure as a result of text removal.
  `void`
  `setCharacterAttributes(int offset, int length, AttributeSet s, boolean replace)`
  Sets attributes for some part of the document.
  `void`
  `setLogicalStyle(int pos, Style s)`
  Sets the logical style to use for the paragraph at the given position.
  `void`
  `setParagraphAttributes(int offset, int length, AttributeSet s, boolean replace)`
  Sets attributes for a paragraph.
  `protected void`
  `styleChanged(Style style)`
  Called when any of this document's styles have changed.

  ### Methods declared in class AbstractDocument

  `addUndoableEditListener, createBranchElement, createLeafElement, createPosition, dump, fireChangedUpdate, fireInsertUpdate, fireRemoveUpdate, fireUndoableEditUpdate, getAsynchronousLoadPriority, getAttributeContext, getBidiRootElement, getContent, getCurrentWriter, getDocumentFilter, getDocumentListeners, getDocumentProperties, getEndPosition, getLength, getListeners, getProperty, getRootElements, getStartPosition, getText, getText, getUndoableEditListeners, insertString, postRemoveUpdate, putProperty, readLock, readUnlock, remove, removeUndoableEditListener, render, replace, setAsynchronousLoadPriority, setDocumentFilter, setDocumentProperties, writeLock, writeUnlock`
  Modifier and Type
  Method
  Description
  `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()`
  Gets the asynchronous loading priority.
  `protected final AbstractDocument.AttributeContext`
  `getAttributeContext()`
  Fetches the context for managing attributes.
  `Element`
  `getBidiRootElement()`
  Returns the root element of the bidirectional structure for this document.
  `protected final AbstractDocument.Content`
  `getContent()`
  Gets the content for the document.
  `protected final Thread`
  `getCurrentWriter()`
  Fetches the current writing thread if there is one.
  `DocumentFilter`
  `getDocumentFilter()`
  Returns the `DocumentFilter` that is responsible for filtering of insertion/removal.
  `DocumentListener[]`
  `getDocumentListeners()`
  Returns an array of all the document listeners registered on this document.
  `Dictionary<Object,Object>`
  `getDocumentProperties()`
  Supports managing a set of properties.
  `final Position`
  `getEndPosition()`
  Returns a position that represents the end of the document.
  `int`
  `getLength()`
  Returns the length of the data.
  `<T extends EventListener>
  T[]`
  `getListeners(Class<T> listenerType)`
  Returns an array of all the objects currently registered as `FooListener`s upon this document.
  `final Object`
  `getProperty(Object key)`
  A convenience method for looking up a property value.
  `Element[]`
  `getRootElements()`
  Gets all root elements defined.
  `final 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)`
  Fetches the text contained within the given portion of the document.
  `UndoableEditListener[]`
  `getUndoableEditListeners()`
  Returns an array of all the undoable edit listeners registered on this document.
  `void`
  `insertString(int offs, String str, AttributeSet a)`
  Inserts some content into the document.
  `protected void`
  `postRemoveUpdate(AbstractDocument.DefaultDocumentEvent chng)`
  Updates any document structure as a result of text removal.
  `final void`
  `putProperty(Object key, Object value)`
  A convenience method for storing up a property value.
  `final void`
  `readLock()`
  Acquires a lock to begin reading some state from the document.
  `final void`
  `readUnlock()`
  Does a read unlock.
  `void`
  `remove(int offs, int len)`
  Removes some content from the document.
  `void`
  `removeUndoableEditListener(UndoableEditListener listener)`
  Removes an undo listener.
  `void`
  `render(Runnable r)`
  This allows the model to be safely rendered in the presence of concurrency, if the model supports being updated asynchronously.
  `void`
  `replace(int offset, int length, String text, AttributeSet attrs)`
  Deletes the region of text from `offset` to `offset + length`, and replaces it with `text`.
  `void`
  `setAsynchronousLoadPriority(int p)`
  Sets the asynchronous loading priority.
  `void`
  `setDocumentFilter(DocumentFilter filter)`
  Sets the `DocumentFilter`.
  `void`
  `setDocumentProperties(Dictionary<Object,Object> x)`
  Replaces the document properties dictionary for this document.
  `protected final void`
  `writeLock()`
  Acquires a lock to begin mutating the document this lock protects.
  `protected final void`
  `writeUnlock()`
  Releases a write lock previously obtained via `writeLock`.

  ### Methods declared in class Object

  `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`
  Modifier and Type
  Method
  Description
  `protected Object`
  `clone()`
  Creates and returns a copy of this object.
  `boolean`
  `equals(Object obj)`
  Indicates whether some other object is "equal to" this one.
  `protected void`
  `finalize()`
  Deprecated, for removal: This API element is subject to removal in a future version.
  Finalization is deprecated and subject to removal in a future release.
  `final Class<?>`
  `getClass()`
  Returns the runtime class of this `Object`.
  `int`
  `hashCode()`
  Returns a hash code value for this object.
  `final void`
  `notify()`
  Wakes up a single thread that is waiting on this object's monitor.
  `final void`
  `notifyAll()`
  Wakes up all threads that are waiting on this object's monitor.
  `String`
  `toString()`
  Returns a string representation of the object.
  `final void`
  `wait()`
  Causes the current thread to wait until it is awakened, typically by being notified or interrupted.
  `final void`
  `wait(long timeoutMillis)`
  Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.
  `final void`
  `wait(long timeoutMillis, int nanos)`
  Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.

- ## Field Details

  - ### BUFFER_SIZE_DEFAULT

    public static final int BUFFER_SIZE_DEFAULT
    The default size of the initial content buffer.
    See Also:
      - Constant Field Values

  - ### buffer

    protected DefaultStyledDocument.ElementBuffer buffer
    The element buffer.

- ## Constructor Details

  - ### DefaultStyledDocument

    public DefaultStyledDocument(AbstractDocument.Content c, StyleContext styles)
    Constructs a styled document.
    Parameters:
      `c` - the container for the content
      `styles` - resources and style definitions which may be shared across documents

  - ### DefaultStyledDocument

    public DefaultStyledDocument(StyleContext styles)
    Constructs a styled document with the default content storage implementation and a shared set of styles.
    Parameters:
      `styles` - the styles

  - ### DefaultStyledDocument

    public DefaultStyledDocument()
    Constructs a default styled document. This buffers input content by a size of BUFFER_SIZE_DEFAULT and has a style context that is scoped by the lifetime of the document and is not shared with other documents.

- ## Method Details

  - ### getDefaultRootElement

    public Element getDefaultRootElement()
    Gets the default root element.
    Specified by:
      `getDefaultRootElement` in interface `Document`
    Specified by:
      `getDefaultRootElement` in class `AbstractDocument`
    Returns:
      the root
    See Also:
      - `Document.getDefaultRootElement()`

  - ### create

    protected void create(DefaultStyledDocument.ElementSpec[] data)
    Initialize the document to reflect the given element structure (i.e. the structure reported by the `getDefaultRootElement` method. If the document contained any data it will first be removed.
    Parameters:
      `data` - the element data

  - ### insert

    protected void insert(int offset, DefaultStyledDocument.ElementSpec[] data) throws BadLocationException
    Inserts new elements in bulk. This is useful to allow parsing with the document in an unlocked state and prepare an element structure modification. This method takes an array of tokens that describe how to update an element structure so the time within a write lock can be greatly reduced in an asynchronous update situation.

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

    Parameters:
      `offset` - the starting offset >= 0
      `data` - the element data
    Throws:
      `BadLocationException` - for an invalid starting offset

  - ### removeElement

    public void removeElement(Element elem)
    Removes an element from this document.

    The element is removed from its parent element, as well as the text in the range identified by the element. If the element isn't associated with the document, `IllegalArgumentException` is thrown.

    As empty branch elements are not allowed in the document, if the element is the sole child, its parent element is removed as well, recursively. This means that when replacing all the children of a particular element, new children should be added before removing old children.

    Element removal results in two events being fired, the `DocumentEvent` for changes in element structure and `UndoableEditEvent` for changes in document content.

    If the element contains end-of-content mark (the last `"\n"` character in document), this character is not removed; instead, preceding leaf element is extended to cover the character. If the last leaf already ends with `"\n",` it is included in content removal.

    If the element is `null,` `NullPointerException` is thrown. If the element structure would become invalid after the removal, for example if the element is the document root element, `IllegalArgumentException` is thrown. If the current element structure is invalid, `IllegalStateException` is thrown.

    Parameters:
      `elem` - the element to remove
    Throws:
      `NullPointerException` - if the element is `null`
      `IllegalArgumentException` - if the element could not be removed
      `IllegalStateException` - if the element structure is invalid
    Since:
      1.7

  - ### addStyle

    public Style addStyle(String nm, Style parent)
    Adds a new style into the logical style hierarchy. Style attributes resolve from bottom up so an attribute specified in a child will override an attribute specified in the parent.
    Specified by:
      `addStyle` in interface `StyledDocument`
    Parameters:
      `nm` - the name of the style (must be unique within the collection of named styles). The name may be null if the style is unnamed, but the caller is responsible for managing the reference returned as an unnamed style can't be fetched by name. An unnamed style may be useful for things like character attribute overrides such as found in a style run.
      `parent` - the parent style. This may be null if unspecified attributes need not be resolved in some other style.
    Returns:
      the style

  - ### removeStyle

    public void removeStyle(String nm)
    Removes a named style previously added to the document.
    Specified by:
      `removeStyle` in interface `StyledDocument`
    Parameters:
      `nm` - the name of the style to remove

  - ### getStyle

    public Style getStyle(String nm)
    Fetches a named style previously added.
    Specified by:
      `getStyle` in interface `StyledDocument`
    Parameters:
      `nm` - the name of the style
    Returns:
      the style

  - ### getStyleNames

    public Enumeration<?> getStyleNames()
    Fetches the list of style names.
    Returns:
      all the style names

  - ### setLogicalStyle

    public void setLogicalStyle(int pos, Style s)
    Sets the logical style to use for the paragraph at the given position. If attributes aren't explicitly set for character and paragraph attributes they will resolve through the logical style assigned to the paragraph, which in turn may resolve through some hierarchy completely independent of the element hierarchy in the document.

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

    Specified by:
      `setLogicalStyle` in interface `StyledDocument`
    Parameters:
      `pos` - the offset from the start of the document >= 0
      `s` - the logical style to assign to the paragraph, null if none

  - ### getLogicalStyle

    public Style getLogicalStyle(int p)
    Fetches the logical style assigned to the paragraph represented by the given position.
    Specified by:
      `getLogicalStyle` in interface `StyledDocument`
    Parameters:
      `p` - the location to translate to a paragraph and determine the logical style assigned >= 0. This is an offset from the start of the document.
    Returns:
      the style, null if none

  - ### setCharacterAttributes

    public void setCharacterAttributes(int offset, int length, AttributeSet s, boolean replace)
    Sets attributes for some part of the document. A write lock is held by this operation while changes are being made, and a DocumentEvent is sent to the listeners after the change has been successfully completed.

    `offset` and `length` define the range of the text over which the attributes are set. If the length is <= 0, then no action is taken and the method just returns. If the offset is <=0 or > the length of the text then no action is taken, and the method just returns. Otherwise if `offset + length` will exceed the length of the text then the affected range is truncated.

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

    Specified by:
      `setCharacterAttributes` in interface `StyledDocument`
    Parameters:
      `offset` - the offset in the document >= 0
      `length` - the length > 0
      `s` - the attributes
      `replace` - true if the previous attributes should be replaced before setting the new attributes

  - ### setParagraphAttributes

    public void setParagraphAttributes(int offset, int length, AttributeSet s, boolean replace)
    Sets attributes for a paragraph.

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

    Specified by:
      `setParagraphAttributes` in interface `StyledDocument`
    Parameters:
      `offset` - the offset into the paragraph >= 0
      `length` - the number of characters affected >= 0
      `s` - the attributes
      `replace` - whether to replace existing attributes, or merge them

  - ### getParagraphElement

    public Element getParagraphElement(int pos)
    Gets the paragraph element at the offset `pos`. A paragraph consists of at least one child Element, which is usually a leaf.
    Specified by:
      `getParagraphElement` in interface `StyledDocument`
    Specified by:
      `getParagraphElement` in class `AbstractDocument`
    Parameters:
      `pos` - the starting offset >= 0
    Returns:
      the element

  - ### getCharacterElement

    public Element getCharacterElement(int pos)
    Gets a character element based on a position.
    Specified by:
      `getCharacterElement` in interface `StyledDocument`
    Parameters:
      `pos` - the position in the document >= 0
    Returns:
      the element

  - ### 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. This implementation simply parses the inserted content for line breaks and builds up a set of instructions for the element buffer.
    Overrides:
      `insertUpdate` in class `AbstractDocument`
    Parameters:
      `chng` - a description of the document change
      `attr` - the attributes

  - ### removeUpdate

    protected void removeUpdate(AbstractDocument.DefaultDocumentEvent chng)
    Updates document structure as a result of text removal.
    Overrides:
      `removeUpdate` in class `AbstractDocument`
    Parameters:
      `chng` - a description of the document change

  - ### createDefaultRoot

    protected AbstractDocument.AbstractElement createDefaultRoot()
    Creates the root element to be used to represent the default document structure.
    Returns:
      the element base

  - ### getForeground

    public Color getForeground(AttributeSet attr)
    Gets the foreground color from an attribute set.
    Specified by:
      `getForeground` in interface `StyledDocument`
    Parameters:
      `attr` - the attribute set
    Returns:
      the color

  - ### getBackground

    public Color getBackground(AttributeSet attr)
    Gets the background color from an attribute set.
    Specified by:
      `getBackground` in interface `StyledDocument`
    Parameters:
      `attr` - the attribute set
    Returns:
      the color

  - ### getFont

    public Font getFont(AttributeSet attr)
    Gets the font from an attribute set.
    Specified by:
      `getFont` in interface `StyledDocument`
    Parameters:
      `attr` - the attribute set
    Returns:
      the font

  - ### styleChanged

    protected void styleChanged(Style style)
    Called when any of this document's styles have changed. Subclasses may wish to be intelligent about what gets damaged.
    Parameters:
      `style` - The Style that has changed.

  - ### addDocumentListener

    public void addDocumentListener(DocumentListener listener)
    Adds a document listener for notification of any changes.
    Specified by:
      `addDocumentListener` in interface `Document`
    Overrides:
      `addDocumentListener` in class `AbstractDocument`
    Parameters:
      `listener` - the listener
    See Also:
      - `Document.addDocumentListener(DocumentListener)`

  - ### removeDocumentListener

    public void removeDocumentListener(DocumentListener listener)
    Removes a document listener.
    Specified by:
      `removeDocumentListener` in interface `Document`
    Overrides:
      `removeDocumentListener` in class `AbstractDocument`
    Parameters:
      `listener` - the listener
    See Also:
      - `Document.removeDocumentListener(DocumentListener)`