Class HTMLDocument
- All Implemented Interfaces:
Serializable, Document, StyledDocument
public class HTMLDocument extends DefaultStyledDocument
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.
setInnerHTML(Element, String)setOuterHTML(Element, String)insertBeforeStart(Element, String)insertAfterStart(Element, String)insertBeforeEnd(Element, String)insertAfterEnd(Element, String)
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.
| Example | insertAfterStart | insertBeforeEnd | insertBeforeStart | insertAfterEnd | setInnerHTML | setOuterHTML |
|---|---|---|---|---|---|---|
| Paragraph 1 Paragraph 2 |
Paragraph 1 Paragraph 2 | Paragraph 1 Paragraph 2
|
Paragraph 1 Paragraph 2 | Paragraph 1 Paragraph 2
|
|
|
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.
Nested Class Summary
| Modifier and Type | Class | Description |
|---|---|---|
class |
HTMLDocument.BlockElement |
An element that represents a structural block of HTML. |
class |
HTMLDocument.HTMLReader |
An HTML reader to load an HTML document with an HTML element structure. |
static class |
HTMLDocument.Iterator |
An iterator to iterate over a particular type of tag. |
class |
HTMLDocument.RunElement |
An element that represents a chunk of text that has a set of HTML character level attributes assigned to it. |
Nested classes/interfaces declared in class DefaultStyledDocument
DefaultStyledDocument.AttributeUndoableEdit, DefaultStyledDocument.ElementBuffer, DefaultStyledDocument.ElementSpec, DefaultStyledDocument.SectionElement | 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
| Modifier and Type | Field | Description |
|---|---|---|
static final String |
AdditionalComments |
Document property key value. |
Fields declared in class DefaultStyledDocument
buffer, BUFFER_SIZE_DEFAULT | 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
| Constructor | Description |
|---|---|
HTMLDocument() |
Constructs an HTML document using the default buffer size and a default StyleSheet. |
HTMLDocument |
Constructs an HTML document with the given content storage implementation and the given style/attribute storage mechanism. |
HTMLDocument |
Constructs an HTML document with the default content storage implementation and the specified style/attribute storage mechanism. |
Method Summary
| Modifier and Type | Method | Description |
|---|---|---|
protected void |
create |
Replaces the contents of the document with the given element specifications. |
protected Element |
createBranchElement |
Creates a document branch element, that can contain other elements. |
protected AbstractDocument.AbstractElement |
createDefaultRoot() |
Creates the root element to be used to represent the default document structure. |
protected Element |
createLeafElement |
Creates a document leaf element that directly represents text (doesn't have any children). |
protected void |
fireChangedUpdate |
Notifies all listeners that have registered interest for notification on this event type. |
protected void |
fireUndoableEditUpdate |
Notifies all listeners that have registered interest for notification on this event type. |
URL |
getBase() |
Returns the location to resolve relative URLs against. |
Element |
getElement |
Returns the element that has the given id Attribute. |
Element |
getElement |
Returns the child element of e that contains the attribute, attribute with value value, or null if one isn't found. |
HTMLDocument.Iterator |
getIterator |
Fetches an iterator for the specified HTML tag. |
HTMLEditorKit.Parser |
getParser() |
Returns the parser that is used when inserting HTML into the existing document. |
boolean |
getPreservesUnknownTags() |
Returns the behavior the parser observes when encountering unknown tags. |
HTMLEditorKit.ParserCallback |
getReader |
Fetches the reader for the parser to use when loading the document with HTML. |
HTMLEditorKit.ParserCallback |
getReader |
Returns the reader for the parser to use to load the document with HTML. |
StyleSheet |
getStyleSheet() |
Fetches the StyleSheet with the document-specific display rules (CSS) that were specified in the HTML document itself. |
int |
getTokenThreshold() |
Gets the number of tokens to buffer before trying to update the documents element structure. |
protected void |
insert |
Inserts new elements in bulk. |
void |
insertAfterEnd |
Inserts the HTML specified as a string after the end of the given element. |
void |
insertAfterStart |
Inserts the HTML specified as a string at the start of the element. |
void |
insertBeforeEnd |
Inserts the HTML specified as a string at the end of the element. |
void |
insertBeforeStart |
Inserts the HTML specified as a string before the start of the given element. |
protected void |
insertUpdate |
Updates document structure as a result of text insertion. |
void |
processHTMLFrameHyperlinkEvent |
Processes HyperlinkEvents that are generated by documents in an HTML frame. |
void |
setBase |
Sets the location to resolve relative URLs against. |
void |
setInnerHTML |
Replaces the children of the given element with the contents specified as an HTML string. |
void |
setOuterHTML |
Replaces the given element in the parent with the contents specified as an HTML string. |
void |
setParagraphAttributes |
Sets attributes for a paragraph. |
void |
setParser |
Sets the parser that is used by the methods that insert html into the existing document, such as setInnerHTML, and setOuterHTML. |
void |
setPreservesUnknownTags |
Determines how unknown tags are handled by the parser. |
void |
setTokenThreshold |
Sets the number of tokens to buffer before trying to update the documents element structure. |
Methods declared in class DefaultStyledDocument
addDocumentListener, addStyle, getBackground, getCharacterElement, getDefaultRootElement, getFont, getForeground, getLogicalStyle, getParagraphElement, getStyle, getStyleNames, removeDocumentListener, removeElement, removeStyle, removeUpdate, setCharacterAttributes, setLogicalStyle, styleChanged | Modifier and Type | Method | Description |
|---|---|---|
void |
addDocumentListener |
Adds a document listener for notification of any changes. |
Style |
addStyle |
Adds a new style into the logical style hierarchy. |
Color |
getBackground |
Gets the background color from an attribute set. |
Element |
getCharacterElement |
Gets a character element based on a position. |
Element |
getDefaultRootElement() |
Gets the default root element. |
Font |
getFont |
Gets the font from an attribute set. |
Color |
getForeground |
Gets the foreground color from an attribute set. |
Style |
getLogicalStyle |
Fetches the logical style assigned to the paragraph represented by the given position. |
Element |
getParagraphElement |
Gets the paragraph element at the offset pos. |
Style |
getStyle |
Fetches a named style previously added. |
Enumeration |
getStyleNames() |
Fetches the list of style names. |
void |
removeDocumentListener |
Removes a document listener. |
void |
removeElement |
Removes an element from this document. |
void |
removeStyle |
Removes a named style previously added to the document. |
protected void |
removeUpdate |
Updates document structure as a result of text removal. |
void |
setCharacterAttributes |
Sets attributes for some part of the document. |
void |
setLogicalStyle |
Sets the logical style to use for the paragraph at the given position. |
protected void |
styleChanged |
Called when any of this document's styles have changed. |
Methods declared in class AbstractDocument
addUndoableEditListener, createPosition, dump, fireInsertUpdate, fireRemoveUpdate, 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 |
Adds an undo listener for notification of any changes. |
Position |
createPosition |
Returns a position that will track change as the document is altered. |
void |
dump |
Gives a diagnostic dump. |
protected void |
fireInsertUpdate |
Notifies all listeners that have registered interest for notification on this event type. |
protected void |
fireRemoveUpdate |
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 |
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> |
getListeners |
Returns an array of all the objects currently registered as FooListeners upon this document. |
final Object |
getProperty |
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 |
Gets a sequence of text from the document. |
void |
getText |
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 |
Inserts some content into the document. |
protected void |
postRemoveUpdate |
Updates any document structure as a result of text removal. |
final void |
putProperty |
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 |
Removes some content from the document. |
void |
removeUndoableEditListener |
Removes an undo listener. |
void |
render |
This allows the model to be safely rendered in the presence of concurrency, if the model supports being updated asynchronously. |
void |
replace |
Deletes the region of text from offset to offset + length, and replaces it with text. |
void |
setAsynchronousLoadPriority |
Sets the asynchronous loading priority. |
void |
setDocumentFilter |
Sets the DocumentFilter. |
void |
setDocumentProperties |
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 |
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 |
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 |
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
AdditionalComments
public static final String AdditionalComments
- See Also:
Constructor Details
HTMLDocument
public HTMLDocument()
StyleSheet. This is a convenience method for the constructor HTMLDocument(Content, StyleSheet).HTMLDocument
public HTMLDocument(StyleSheet styles)
HTMLDocument(Content, StyleSheet).- Parameters:
-
styles- the styles
HTMLDocument
public HTMLDocument(AbstractDocument.Content c, StyleSheet styles)
- Parameters:
-
c- the container for the content -
styles- the styles
Method Details
getReader
public HTMLEditorKit.ParserCallback getReader(int pos)
HTMLDocument.HTMLReader. Subclasses can reimplement this method to change how the document gets structured if desired. (For example, to handle custom tags, or structurally represent character style elements.)- Parameters:
-
pos- the starting position - Returns:
- the reader used by the parser to load the document
getReader
public HTMLEditorKit.ParserCallback getReader(int pos, int popDepth, int pushDepth, HTML.Tag insertTag)
HTMLDocument.HTMLReader. Subclasses can reimplement this method to change how the document gets structured if desired. (For example, to handle custom tags, or structurally represent character style elements.) This is a convenience method for getReader(int, int, int, HTML.Tag, TRUE).
- Parameters:
-
pos- the starting position -
popDepth- the number ofElementSpec.EndTagTypesto generate before inserting -
pushDepth- the number ofElementSpec.StartTagTypeswith a direction ofElementSpec.JoinNextDirectionthat should be generated before inserting, but after the end tags have been generated -
insertTag- the first tag to start inserting into document - Returns:
- the reader used by the parser to load the document
getBase
public URL getBase()
- Returns:
- the base location
setBase
public void setBase(URL u)
This also sets the base of the StyleSheet to be u as well as the base of the document.
- Parameters:
-
u- the desired base URL
insert
protected void insert(int offset, DefaultStyledDocument.ElementSpec[] data) throws BadLocationException
- Overrides:
-
insertin classDefaultStyledDocument - Parameters:
-
offset- the starting offset -
data- the element data - Throws:
-
BadLocationException- if the given position does not represent a valid location in the associated document.
insertUpdate
protected void insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr)
- Overrides:
-
insertUpdatein classDefaultStyledDocument - Parameters:
-
chng- a description of the document change -
attr- the attributes
create
protected void create(DefaultStyledDocument.ElementSpec[] data)
- Overrides:
-
createin classDefaultStyledDocument - Parameters:
-
data- the new contents of the document
setParagraphAttributes
public void setParagraphAttributes(int offset, int length, AttributeSet s, boolean replace)
This method is thread safe, although most Swing methods are not. Please see Concurrency in Swing for more information.
- Specified by:
-
setParagraphAttributesin interfaceStyledDocument - Overrides:
-
setParagraphAttributesin classDefaultStyledDocument - Parameters:
-
offset- the offset into the paragraph (must be at least 0) -
length- the number of characters affected (must be at least 0) -
s- the attributes -
replace- whether to replace existing attributes, or merge them
getStyleSheet
public StyleSheet getStyleSheet()
StyleSheet with the document-specific display rules (CSS) that were specified in the HTML document itself.- Returns:
- the
StyleSheet
getIterator
public HTMLDocument.Iterator getIterator(HTML.Tag t)
- Parameters:
-
t- the requestedHTML.Tag - Returns:
- the
Iteratorfor the given HTML tag - See Also:
createLeafElement
protected Element createLeafElement(Element parent, AttributeSet a, int p0, int p1)
HTMLDocument.RunElement.- Overrides:
-
createLeafElementin classAbstractDocument - Parameters:
-
parent- the parent element -
a- the attributes for the element -
p0- the beginning of the range (must be at least 0) -
p1- the end of the range (must be at least p0) - Returns:
- the new element
createBranchElement
protected Element createBranchElement(Element parent, AttributeSet a)
HTMLDocument.BlockElement.- Overrides:
-
createBranchElementin classAbstractDocument - Parameters:
-
parent- the parent element -
a- the attributes - Returns:
- the element
createDefaultRoot
protected AbstractDocument.AbstractElement createDefaultRoot()
- Overrides:
-
createDefaultRootin classDefaultStyledDocument - Returns:
- the element base
setTokenThreshold
public void setTokenThreshold(int n)
- Parameters:
-
n- the number of tokens to buffer
getTokenThreshold
public int getTokenThreshold()
Integer.MAX_VALUE.- Returns:
- the number of tokens to buffer
setPreservesUnknownTags
public void setPreservesUnknownTags(boolean preservesTags)
- Parameters:
-
preservesTags- true if unknown tags should be saved in the model, otherwise tags are dropped - See Also:
getPreservesUnknownTags
public boolean getPreservesUnknownTags()
- Returns:
- true if unknown tags are to be preserved when parsing
- See Also:
processHTMLFrameHyperlinkEvent
public void processHTMLFrameHyperlinkEvent(HTMLFrameHyperlinkEvent e)
HyperlinkEvents that are generated by documents in an HTML frame. The HyperlinkEvent type, as the parameter suggests, is HTMLFrameHyperlinkEvent. In addition to the typical information contained in a HyperlinkEvent, this event contains the element that corresponds to the frame in which the click happened (the source element) and the target name. The target name has 4 possible values: - _self
- _parent
- _top
- a named frame
HTML.Attribute.SRC attribute and fires a ChangedUpdate event. If the target is _parent, then it deletes the parent element, which is a <FRAMESET> element, and inserts a new <FRAME> element, and sets its HTML.Attribute.SRC attribute to have a value equal to the destination URL and fire a RemovedUpdate and InsertUpdate.
If the target is _top, this method does nothing. In the implementation of the view for a frame, namely the FrameView, the processing of _top is handled. Given that _top implies replacing the entire document, it made sense to handle this outside of the document that it will replace.
If the target is a named frame, then the element hierarchy is searched for an element with a name equal to the target, its HTML.Attribute.SRC attribute is updated and a ChangedUpdate event is fired.
- Parameters:
-
e- the event
setParser
public void setParser(HTMLEditorKit.Parser parser)
setInnerHTML, and setOuterHTML. HTMLEditorKit.createDefaultDocument will set the parser for you. If you create an HTMLDocument by hand, be sure and set the parser accordingly.
- Parameters:
-
parser- the parser to be used for text insertion - Since:
- 1.3
getParser
public HTMLEditorKit.Parser getParser()
- Returns:
- the parser used for text insertion
- Since:
- 1.3
setInnerHTML
public void setInnerHTML(Element elem, String htmlText) throws BadLocationException, IOException
This will be seen as at least two events, n inserts followed by a remove.
Consider the following structure (the elem parameter is in bold).
<body>
|
<div>
/ \
<p> <p>
Invoking setInnerHTML(elem, "<ul><li>") results in the following structure (new elements are in blue).
<body>
|
<div>
\
<ul>
\
<li>
Parameter elem must not be a leaf element, otherwise an IllegalArgumentException is thrown. If either elem or htmlText parameter is null, no changes are made to the document.
For this to work correctly, the document must have an HTMLEditorKit.Parser set. This will be the case if the document was created from an HTMLEditorKit via the createDefaultDocument method.
- Parameters:
-
elem- the branch element whose children will be replaced -
htmlText- the string to be parsed and assigned toelem - Throws:
-
IllegalArgumentException- ifelemis a leaf -
IllegalStateException- if anHTMLEditorKit.Parserhas not been defined -
BadLocationException- if replacement is impossible because of a structural issue -
IOException- if an I/O exception occurs - Since:
- 1.3
setOuterHTML
public void setOuterHTML(Element elem, String htmlText) throws BadLocationException, IOException
This will be seen as at least two events, n inserts followed by a remove.
When replacing a leaf this will attempt to make sure there is a newline present if one is needed. This may result in an additional element being inserted. Consider, if you were to replace a character element that contained a newline with <img> this would create two elements, one for the image, and one for the newline.
If you try to replace the element at length you will most likely end up with two elements, eg setOuterHTML(getCharacterElement (getLength()),
"blah") will result in two leaf elements at the end, one representing 'blah', and the other representing the end element.
Consider the following structure (the elem parameter is in bold).
<body>
|
<div>
/ \
<p> <p>
Invoking setOuterHTML(elem, "<ul><li>") results in the following structure (new elements are in blue).
<body>
|
<ul>
\
<li>
If either elem or htmlText parameter is null, no changes are made to the document.
For this to work correctly, the document must have an HTMLEditorKit.Parser set. This will be the case if the document was created from an HTMLEditorKit via the createDefaultDocument method.
- Parameters:
-
elem- the element to replace -
htmlText- the string to be parsed and inserted in place ofelem - Throws:
-
IllegalStateException- if an HTMLEditorKit.Parser has not been set -
BadLocationException- if replacement is impossible because of a structural issue -
IOException- if an I/O exception occurs - Since:
- 1.3
insertAfterStart
public void insertAfterStart(Element elem, String htmlText) throws BadLocationException, IOException
Consider the following structure (the elem parameter is in bold).
<body>
|
<div>
/ \
<p> <p>
Invoking insertAfterStart(elem,
"<ul><li>") results in the following structure (new elements are in blue).
<body>
|
<div>
/ | \
<ul> <p> <p>
/
<li>
Unlike the insertBeforeStart method, new elements become children of the specified element, not siblings.
Parameter elem must not be a leaf element, otherwise an IllegalArgumentException is thrown. If either elem or htmlText parameter is null, no changes are made to the document.
For this to work correctly, the document must have an HTMLEditorKit.Parser set. This will be the case if the document was created from an HTMLEditorKit via the createDefaultDocument method.
- Parameters:
-
elem- the branch element to be the root for the new text -
htmlText- the string to be parsed and assigned toelem - Throws:
-
IllegalArgumentException- ifelemis a leaf -
IllegalStateException- if an HTMLEditorKit.Parser has not been set on the document -
BadLocationException- if insertion is impossible because of a structural issue -
IOException- if an I/O exception occurs - Since:
- 1.3
insertBeforeEnd
public void insertBeforeEnd(Element elem, String htmlText) throws BadLocationException, IOException
If elem's children are leaves, and the character at a elem.getEndOffset() - 1 is a newline, this will insert before the newline so that there isn't text after the newline.
Consider the following structure (the elem parameter is in bold).
<body>
|
<div>
/ \
<p> <p>
Invoking insertBeforeEnd(elem, "<ul><li>") results in the following structure (new elements are in blue).
<body>
|
<div>
/ | \
<p> <p> <ul>
\
<li>
Unlike the insertAfterEnd method, new elements become children of the specified element, not siblings.
Parameter elem must not be a leaf element, otherwise an IllegalArgumentException is thrown. If either elem or htmlText parameter is null, no changes are made to the document.
For this to work correctly, the document must have an HTMLEditorKit.Parser set. This will be the case if the document was created from an HTMLEditorKit via the createDefaultDocument method.
- Parameters:
-
elem- the element to be the root for the new text -
htmlText- the string to be parsed and assigned toelem - Throws:
-
IllegalArgumentException- ifelemis a leaf -
IllegalStateException- if an HTMLEditorKit.Parser has not been set on the document -
BadLocationException- if insertion is impossible because of a structural issue -
IOException- if an I/O exception occurs - Since:
- 1.3
insertBeforeStart
public void insertBeforeStart(Element elem, String htmlText) throws BadLocationException, IOException
Consider the following structure (the elem parameter is in bold).
<body>
|
<div>
/ \
<p> <p>
Invoking insertBeforeStart(elem,
"<ul><li>") results in the following structure (new elements are in blue).
<body>
/ \
<ul> <div>
/ / \
<li> <p> <p>
Unlike the insertAfterStart method, new elements become siblings of the specified element, not children.
If either elem or htmlText parameter is null, no changes are made to the document.
For this to work correctly, the document must have an HTMLEditorKit.Parser set. This will be the case if the document was created from an HTMLEditorKit via the createDefaultDocument method.
- Parameters:
-
elem- the element the content is inserted before -
htmlText- the string to be parsed and inserted beforeelem - Throws:
-
IllegalStateException- if an HTMLEditorKit.Parser has not been set on the document -
BadLocationException- if insertion is impossible because of a structural issue -
IOException- if an I/O exception occurs - Since:
- 1.3
insertAfterEnd
public void insertAfterEnd(Element elem, String htmlText) throws BadLocationException, IOException
Consider the following structure (the elem parameter is in bold).
<body>
|
<div>
/ \
<p> <p>
Invoking insertAfterEnd(elem, "<ul><li>") results in the following structure (new elements are in blue).
<body>
/ \
<div> <ul>
/ \ \
<p> <p> <li>
Unlike the insertBeforeEnd method, new elements become siblings of the specified element, not children.
If either elem or htmlText parameter is null, no changes are made to the document.
For this to work correctly, the document must have an HTMLEditorKit.Parser set. This will be the case if the document was created from an HTMLEditorKit via the createDefaultDocument method.
- Parameters:
-
elem- the element the content is inserted after -
htmlText- the string to be parsed and inserted afterelem - Throws:
-
IllegalStateException- if an HTMLEditorKit.Parser has not been set on the document -
BadLocationException- if insertion is impossible because of a structural issue -
IOException- if an I/O exception occurs - Since:
- 1.3
getElement
public Element getElement(String id)
Attribute. If the element can't be found, null is returned. Note that this method works on an Attribute, not a character tag. In the following HTML snippet: <a id="HelloThere"> the attribute is 'id' and the character tag is 'a'. This is a convenience method for getElement(RootElement, HTML.Attribute.id, id). This is not thread-safe.- Parameters:
-
id- the string representing the desiredAttribute - Returns:
- the element with the specified
Attributeornullif it can't be found, ornullifidisnull - Since:
- 1.3
- See Also:
getElement
public Element getElement(Element e, Object attribute, Object value)
e that contains the attribute, attribute with value value, or null if one isn't found. This is not thread-safe.- Parameters:
-
e- the root element where the search begins -
attribute- the desiredAttribute -
value- the values for the specifiedAttribute - Returns:
- the element with the specified
Attributeand the specifiedvalue, ornullif it can't be found - Since:
- 1.3
- See Also:
fireChangedUpdate
protected void fireChangedUpdate(DocumentEvent e)
- Overrides:
-
fireChangedUpdatein classAbstractDocument - Parameters:
-
e- the event - See Also:
fireUndoableEditUpdate
protected void fireUndoableEditUpdate(UndoableEditEvent e)
- Overrides:
-
fireUndoableEditUpdatein classAbstractDocument - Parameters:
-
e- the event - See Also:
© 1993, 2025, Oracle and/or its affiliates. All rights reserved.
Documentation extracted from Debian's OpenJDK Development Kit package.
Licensed under the GNU General Public License, version 2, with the Classpath Exception.
Various third party code in OpenJDK is licensed under different licenses (see Debian package).
Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.