APIdia Launch Partner
Top Description Inners Fields Constructors Methods
javax.swing.text.html

public Class HTMLDocument

extends DefaultStyledDocument
Class Inheritance
Known Direct Subclasses
javax.swing.plaf.basic.BasicHTML.BasicDocument
Annotations
@SuppressWarnings:serial
Imports
java.awt.font.TextAttribute, java.io.IOException, .StringReader, java.net.MalformedURLException, .URL, java.util.ArrayList, .Enumeration, .HashMap, .Hashtable, .Stack, .Vector, javax.swing.ButtonGroup, .DefaultButtonModel, .DefaultComboBoxModel, .DefaultListModel, .JToggleButton, .ListSelectionModel, javax.swing.event.DocumentEvent, .EventListenerList, .UndoableEditEvent, javax.swing.text.AbstractDocument, .AttributeSet, .BadLocationException, .DefaultEditorKit, .DefaultStyledDocument, .Document, .Element, .ElementIterator, .GapContent, .MutableAttributeSet, .PlainDocument, .SimpleAttributeSet, .StyleConstants, javax.swing.undo.UndoableEdit, sun.swing.SwingUtilities2

A document that models HTML. The purpose of this model is to support both browsing and editing. As a result, the structure described by an HTML document is not exactly replicated by default. The element structure that is modeled by default, is built by the class HTMLDocument.HTMLReader, which implements the HTMLEditorKit.ParserCallback protocol that the parser expects. To change the structure one can subclass HTMLReader, and reimplement the method getReader(int) to return the new reader implementation. The documentation for HTMLReader should be consulted for the details of the default structure created. The intent is that the document be non-lossy (although reproducing the HTML format may result in a different format).

The document models only HTML, and makes no attempt to store view attributes in it. The elements are identified by the StyleContext.NameAttribute attribute, which should always have a value of type HTML.Tag that identifies the kind of element. Some of the elements (such as comments) are synthesized. The HTMLFactory uses this attribute to determine what kind of view to build.

This document supports incremental loading. The TokenThreshold property controls how much of the parse is buffered before trying to update the element structure of the document. This property is set by the EditorKit so that subclasses can disable it.

The Base property determines the URL against which relative URLs are resolved. By default, this will be the Document.StreamDescriptionProperty if the value of the property is a URL. If a <BASE> tag is encountered, the base will become the URL specified by that tag. Because the base URL is a property, it can of course be set directly.

The default content storage mechanism for this document is a gap buffer (GapContent). Alternatives can be supplied by using the constructor that takes a Content implementation.

Modifying HTMLDocument

In addition to the methods provided by Document and StyledDocument for mutating an HTMLDocument, HTMLDocument provides a number of convenience methods. The following methods can be used to insert HTML content into an existing document.

The following examples illustrate using these methods. Each example assumes the HTML document is initialized in the following way:

JEditorPane p = new JEditorPane();
p.setContentType("text/html");
p.setText("..."); // Document text is provided below.
HTMLDocument d = (HTMLDocument) p.getDocument();

With the following HTML content:

<html>
  <head>
    <title>An example HTMLDocument</title>
    <style type="text/css">
      div { background-color: silver; }
      ul { color: blue; }
    </style>
  </head>
  <body>
    <div id="BOX">
      <p>Paragraph 1</p>
      <p>Paragraph 2</p>
    </div>
  </body>
</html>

All the methods for modifying an HTML document require an Element. Elements can be obtained from an HTML document by using the method getElement(Element e, Object attribute, Object value). It returns the first descendant element that contains the specified attribute with the given value, in depth-first order. For example, d.getElement(d.getDefaultRootElement(), StyleConstants.NameAttribute, HTML.Tag.P) returns the first paragraph element.

A convenient shortcut for locating elements is the method getElement(String); returns an element whose ID attribute matches the specified value. For example, d.getElement("BOX") returns the DIV element.

The getIterator(HTML.Tag t) method can also be used for finding all occurrences of the specified HTML tag in the document.

Inserting elements

Elements can be inserted before or after the existing children of any non-leaf element by using the methods insertAfterStart and insertBeforeEnd. For example, if e is the DIV element, d.insertAfterStart(e, "<ul><li>List Item</li></ul>") inserts the list before the first paragraph, and d.insertBeforeEnd(e, "<ul><li>List Item</li></ul>") inserts the list after the last paragraph. The DIV block becomes the parent of the newly inserted elements.

Sibling elements can be inserted before or after any element by using the methods insertBeforeStart and insertAfterEnd. For example, if e is the DIV element, d.insertBeforeStart(e, "<ul><li>List Item</li></ul>") inserts the list before the DIV element, and d.insertAfterEnd(e, "<ul><li>List Item</li></ul>") inserts the list after the DIV element. The newly inserted elements become siblings of the DIV element.

Replacing elements

Elements and all their descendants can be replaced by using the methods setInnerHTML and setOuterHTML. For example, if e is the DIV element, d.setInnerHTML(e, "<ul><li>List Item</li></ul>") replaces all children paragraphs with the list, and d.setOuterHTML(e, "<ul><li>List Item</li></ul>") replaces the DIV element itself. In latter case the parent of the list is the BODY element.

Summary

The following table shows the example document and the results of various methods described above.

HTML Content of example above
Example insertAfterStart insertBeforeEnd insertBeforeStart insertAfterEnd setInnerHTML setOuterHTML

Paragraph 1

Paragraph 2

  • List Item

Paragraph 1

Paragraph 2

Paragraph 1

Paragraph 2

  • List Item
  • List Item

Paragraph 1

Paragraph 2

Paragraph 1

Paragraph 2

  • List Item
  • List Item
  • List Item

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 java.beans.XMLEncoder.

Authors
Timothy Prinzing, Scott Violet, Sunita Mani

Nested and Inner Type Summary

Modifier and TypeClass and Description
public class
HTMLDocument.BlockElement

An element that represents a structural block of HTML.

private static class
HTMLDocument.FixedLengthDocument

Document that allows you to set the maximum length of the text.

public class
HTMLDocument.HTMLReader

An HTML reader to load an HTML document with an HTML element structure.

public abstract static class
HTMLDocument.Iterator

An iterator to iterate over a particular type of tag.

pack-priv static class
HTMLDocument.LeafIterator

An iterator to iterate over a particular type of tag.

public class
HTMLDocument.RunElement

An element that represents a chunk of text that has a set of HTML character level attributes assigned to it.

pack-priv static class
HTMLDocument.TaggedAttributeSet

Used by StyleSheet to determine when to avoid removing HTML.Tags matching StyleConstants.

Field Summary

Modifier and TypeField and Description
public static final String
AdditionalComments

Document property key value.

pack-priv URL
base

The location to resolve relative URLs against.

private String
baseTarget

BASE tag's TARGET attribute value

private static AttributeSet
contentAttributeSet

Used for inserts when a null AttributeSet is supplied.

private boolean
pack-priv boolean
hasBaseTag

does the document have base tag

private static final String
private boolean
insertInBody

Indicates that direct insertion to body section takes place.

pack-priv static String
MAP_PROPERTY

Property Maps are registered under, will be a Hashtable.

private static final int
private static char[]
private HTMLEditorKit.Parser
parser

The parser that is used when inserting html into the existing document.

private boolean
private HashMap<String, ButtonGroup>
private static final int
pack-priv static final String
StyleType

Document property key value.

pack-priv static final String
TokenThreshold

Document property for the number of tokens to buffer before building an element subtree to represent them.

Inherited from javax.swing.text.DefaultStyledDocument:
bufferBUFFER_SIZE_DEFAULT

Constructor Summary

AccessConstructor and Description
public
HTMLDocument()

Constructs an HTML document using the default buffer size and a default StyleSheet.

public
HTMLDocument(StyleSheet
the styles
styles
)

Constructs an HTML document with the default content storage implementation and the specified style/attribute storage mechanism.

public
HTMLDocument(AbstractDocument.Content
the container for the content
c
,
StyleSheet
the styles
styles
)

Constructs an HTML document with the given content storage implementation and the given style/attribute storage mechanism.

Method Summary

Modifier and TypeMethod and Description
pack-priv void
addMap(Map
the Map to be registered
map
)

Adds the specified map, this will remove a Map that has been previously registered with the same name.

protected void
create(DefaultStyledDocument.ElementSpec[]
the new contents of the document
data
)

Overrides javax.swing.text.DefaultStyledDocument.create.

Replaces the contents of the document with the given element specifications.

protected Element

Returns:

the element
createBranchElement
(Element
the parent element
parent
,
AttributeSet
the attributes
a
)

Overrides javax.swing.text.AbstractDocument.createBranchElement.

Creates a document branch element, that can contain other elements.

protected AbstractDocument.AbstractElement

Returns:

the element base
createDefaultRoot
()

Overrides javax.swing.text.DefaultStyledDocument.createDefaultRoot.

Creates the root element to be used to represent the default document structure.

protected Element

Returns:

the new element
createLeafElement
(Element
the parent element
parent
,
AttributeSet
the attributes for the element
a
,
int
the beginning of the range (must be at least 0)
p0
,
int
the end of the range (must be at least p0)
p1
)

Overrides javax.swing.text.AbstractDocument.createLeafElement.

Creates a document leaf element that directly represents text (doesn't have any children).

private Element

Returns:

the element whose NAME attribute has a value of frameName; returns null if not found
findFrame
(String frameName)

Searches the element hierarchy for an FRAME element that has its name attribute equal to the frameName.

protected void
fireChangedUpdate(DocumentEvent
the event
e
)

Overrides javax.swing.text.AbstractDocument.fireChangedUpdate.

Notifies all listeners that have registered interest for notification on this event type.

protected void
fireUndoableEditUpdate(UndoableEditEvent
the event
e
)

Overrides javax.swing.text.AbstractDocument.fireUndoableEditUpdate.

Notifies all listeners that have registered interest for notification on this event type.

public URL

Returns:

the base location
getBase
()

Returns the location to resolve relative URLs against.

pack-priv String
pack-priv String

Returns:

the content type language used for the style sheets
getDefaultStyleSheetType
()

Returns the content type language used for style sheets.

public Element

Returns:

the element with the specified Attribute or null if it can't be found, or null if id is null
getElement
(String
the string representing the desired Attribute
id
)

Returns the element that has the given id Attribute.

public Element

Returns:

the element with the specified Attribute and the specified value, or null if it can't be found
getElement
(Element
the root element where the search begins
e
,
Object
the desired Attribute
attribute
,
Object
the values for the specified Attribute
value
)

Returns the child element of e that contains the attribute, attribute with value value, or null if one isn't found.

private Element

Returns:

the element with the specified Attribute and the specified value, or null if it can't be found
getElement
(Element
the root element where the search begins
e
,
Object
the desired Attribute
attribute
,
Object
the values for the specified Attribute
value
,
boolean searchLeafAttributes)

Returns the child element of e that contains the attribute, attribute with value value, or null if one isn't found.

public HTMLDocument.Iterator

Returns:

the Iterator for the given HTML tag
getIterator
(HTML.Tag
the requested HTML.Tag
t
)

Fetches an iterator for the specified HTML tag.

pack-priv Map

Returns:

the Map or null if it can't be found, or if name is null
getMap
(String
the name of the desired Map
name
)

Returns the Map associated with the given name.

pack-priv Enumeration<Object>

Returns:

the enumerated list of maps, or null if the maps are not an instance of Hashtable
getMaps
()

Returns an Enumeration of the possible Maps.

public HTMLEditorKit.Parser

Returns:

the parser used for text insertion
getParser
()

Returns the parser that is used when inserting HTML into the existing document.

public boolean

Returns:

true if unknown tags are to be preserved when parsing
getPreservesUnknownTags
()

Returns the behavior the parser observes when encountering unknown tags.

public HTMLEditorKit.ParserCallback

Returns:

the reader used by the parser to load the document
getReader
(int
the starting position
pos
)

Fetches the reader for the parser to use when loading the document with HTML.

public HTMLEditorKit.ParserCallback

Returns:

the reader used by the parser to load the document
getReader
(int
the starting position
pos
,
int
the number of ElementSpec.EndTagTypes to generate before inserting
popDepth
,
int
the number of ElementSpec.StartTagTypes with a direction of ElementSpec.JoinNextDirection that should be generated before inserting, but after the end tags have been generated
pushDepth
,
HTML.Tag
the first tag to start inserting into document
insertTag
)

Returns the reader for the parser to use to load the document with HTML.

pack-priv HTMLEditorKit.ParserCallback

Returns:

the reader used by the parser to load the document
getReader
(int pos, int
the number of ElementSpec.EndTagTypes to generate before inserting
popDepth
,
int
the number of ElementSpec.StartTagTypes with a direction of ElementSpec.JoinNextDirection that should be generated before inserting, but after the end tags have been generated
pushDepth
,
HTML.Tag
the first tag to start inserting into document
insertTag
,
boolean
false if all the Elements after insertTag should be inserted; otherwise insertTag will be inserted
insertInsertTag
)

Fetches the reader for the parser to use to load the document with HTML.

public StyleSheet

Returns:

the StyleSheet
getStyleSheet
()

Fetches the StyleSheet with the document-specific display rules (CSS) that were specified in the HTML document itself.

public int

Returns:

the number of tokens to buffer
getTokenThreshold
()

Gets the number of tokens to buffer before trying to update the documents element structure.

pack-priv boolean
protected void
insert(int
the starting offset
offset
,
DefaultStyledDocument.ElementSpec[]
the element data
data
)

Overrides javax.swing.text.DefaultStyledDocument.insert.

Inserts new elements in bulk.

public void
insertAfterEnd(Element
the element the content is inserted after
elem
,
String
the string to be parsed and inserted after elem
htmlText
)

Inserts the HTML specified as a string after the end of the given element.

public void
insertAfterStart(Element
the branch element to be the root for the new text
elem
,
String
the string to be parsed and assigned to elem
htmlText
)

Inserts the HTML specified as a string at the start of the element.

public void
insertBeforeEnd(Element
the element to be the root for the new text
elem
,
String
the string to be parsed and assigned to elem
htmlText
)

Inserts the HTML specified as a string at the end of the element.

public void
insertBeforeStart(Element
the element the content is inserted before
elem
,
String
the string to be parsed and inserted before elem
htmlText
)

Inserts the HTML specified as a string before the start of the given element.

private void
insertHTML(Element parent, int offset, String html, boolean wantsTrailingNewline)

Inserts a string of HTML into the document at the given position.

protected void
insertUpdate(AbstractDocument.DefaultDocumentEvent
a description of the document change
chng
,
AttributeSet
the attributes
attr
)

Overrides javax.swing.text.DefaultStyledDocument.insertUpdate.

Updates document structure as a result of text insertion.

private void
installParserIfNecessary()

Installs a default Parser if one has not been installed yet.

pack-priv boolean

Returns:

true if document will be viewed in a frame, otherwise false
isFrameDocument
()

Returns true if the document will be viewed in a frame.

pack-priv static boolean

Returns:

true if there is a match, false otherwise
matchNameAttribute
(AttributeSet
the attributes to be matched
attr
,
HTML.Tag
the value to be matched
tag
)

Returns true if StyleConstants.NameAttribute is equal to the tag that is passed in as a parameter.

pack-priv void
public void
processHTMLFrameHyperlinkEvent(HTMLFrameHyperlinkEvent
the event
e
)

Processes HyperlinkEvents that are generated by documents in an HTML frame.

pack-priv void
private void
removeElements(Element e, int index, int count)

Removes child Elements of the passed in Element e.

private void
removeElements(Element e, int index, int count, int start, int end)

Called to remove child Elements when the end is not touched.

private void
removeElementsAtEnd(Element e, int index, int count, int start, int end)

Called to remove child elements of e when one of the elements to remove is representing the end character.

pack-priv void
removeMap(Map
the Map to be removed
map
)

Removes a previously registered map.

private void
replace(AbstractDocument.DefaultDocumentEvent dde, Element e, int index, int count, int start, int end, boolean remove, boolean create)

This is used by removeElementsAtEnd, it removes count elements starting at start from e.

public void
setBase(URL
the desired base URL
u
)

Sets the location to resolve relative URLs against.

pack-priv void
setDefaultStyleSheetType(String
the content type language for the style sheets
contentType
)

Sets the content type language used for style sheets that do not explicitly specify the type.

pack-priv void
setFrameDocumentState(boolean
true if the document will be viewed in a frame, otherwise false
frameDoc
)

Sets a boolean state about whether the document will be viewed in a frame.

public void
setInnerHTML(Element
the branch element whose children will be replaced
elem
,
String
the string to be parsed and assigned to elem
htmlText
)

Replaces the children of the given element with the contents specified as an HTML string.

public void
setOuterHTML(Element
the element to replace
elem
,
String
the string to be parsed and inserted in place of elem
htmlText
)

Replaces the given element in the parent with the contents specified as an HTML string.

public void
setParagraphAttributes(int
the offset into the paragraph (must be at least 0)
offset
,
int
the number of characters affected (must be at least 0)
length
,
AttributeSet
the attributes
s
,
boolean
whether to replace existing attributes, or merge them
replace
)

Overrides javax.swing.text.DefaultStyledDocument.setParagraphAttributes.

Implements javax.swing.text.StyledDocument.setParagraphAttributes.

Sets attributes for a paragraph.

public void
setParser(HTMLEditorKit.Parser
the parser to be used for text insertion
parser
)

Sets the parser that is used by the methods that insert html into the existing document, such as setInnerHTML, and setOuterHTML.

public void
setPreservesUnknownTags(boolean
true if unknown tags should be saved in the model, otherwise tags are dropped
preservesTags
)

Determines how unknown tags are handled by the parser.

public void
setTokenThreshold(int
the number of tokens to buffer
n
)

Sets the number of tokens to buffer before trying to update the documents element structure.

private void
updateFrame(Element
a FRAME element whose SRC attribute will be updated
element
,
String
a string specifying the new value for the SRC attribute
url
)

Updates the Frame elements HTML.Attribute.SRC attribute and fires a ChangedUpdate event.

private void
updateFrameSet(Element
the frameset element to remove
element
,
String
the value for the SRC attribute for the new frame that will replace the frameset
url
)

Replaces a frameset branch Element with a frame leaf element.

private void
verifyParser()

Verifies the document has an HTMLEditorKit.Parser set.

Inherited from javax.swing.text.DefaultStyledDocument:
addDocumentListeneraddStylegetBackgroundgetCharacterElementgetDefaultRootElementgetFontgetForegroundgetLogicalStylegetParagraphElementgetStylegetStyleNamesremoveDocumentListenerremoveElementremoveStyleremoveUpdatesetCharacterAttributessetLogicalStylestyleChanged