- java.lang.Object
-
- javax.swing.text.AbstractDocument
-
- javax.swing.text.DefaultStyledDocument
-
- javax.swing.text.html.HTMLDocument
-
- All Implemented Interfaces:
Serializable,Document,StyledDocument
public class HTMLDocument extends DefaultStyledDocument
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 classHTMLDocument.HTMLReader, which implements theHTMLEditorKit.ParserCallbackprotocol that the parser expects. To change the structure one can subclassHTMLReader, and reimplement the methodgetReader(int)to return the new reader implementation. The documentation forHTMLReadershould 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.NameAttributeattribute, which should always have a value of typeHTML.Tagthat identifies the kind of element. Some of the elements (such as comments) are synthesized. TheHTMLFactoryuses this attribute to determine what kind of view to build.This document supports incremental loading. The
TokenThresholdproperty controls how much of the parse is buffered before trying to update the element structure of the document. This property is set by theEditorKitso that subclasses can disable it.The
Baseproperty determines the URL against which relative URLs are resolved. By default, this will be theDocument.StreamDescriptionPropertyif 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 aContentimplementation.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 methodgetElement(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 whoseIDattribute matches the specified value. For example,d.getElement("BOX")returns theDIVelement.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
insertAfterStartandinsertBeforeEnd. For example, ifeis theDIVelement,d.insertAfterStart(e, "<ul><li>List Item</li></ul>")inserts the list before the first paragraph, andd.insertBeforeEnd(e, "<ul><li>List Item</li></ul>")inserts the list after the last paragraph. TheDIVblock becomes the parent of the newly inserted elements.Sibling elements can be inserted before or after any element by using the methods
insertBeforeStartandinsertAfterEnd. For example, ifeis theDIVelement,d.insertBeforeStart(e, "<ul><li>List Item</li></ul>")inserts the list before theDIVelement, andd.insertAfterEnd(e, "<ul><li>List Item</li></ul>")inserts the list after theDIVelement. The newly inserted elements become siblings of theDIVelement.Replacing elements
Elements and all their descendants can be replaced by using the methods
setInnerHTMLandsetOuterHTML. For example, ifeis theDIVelement,d.setInnerHTML(e, "<ul><li>List Item</li></ul>")replaces all children paragraphs with the list, andd.setOuterHTML(e, "<ul><li>List Item</li></ul>")replaces theDIVelement itself. In latter case the parent of the list is theBODYelement.Summary
The following table shows the example document and the results of various methods described above.
HTML Content of example above Example insertAfterStartinsertBeforeEndinsertBeforeStartinsertAfterEndsetInnerHTMLsetOuterHTMLParagraph 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.beanspackage. Please seeXMLEncoder.- See Also:
- Serialized Form
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description classHTMLDocument.BlockElementAn element that represents a structural block of HTML.classHTMLDocument.HTMLReaderAn HTML reader to load an HTML document with an HTML element structure.static classHTMLDocument.IteratorAn iterator to iterate over a particular type of tag.classHTMLDocument.RunElementAn 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 javax.swing.text.DefaultStyledDocument
DefaultStyledDocument.AttributeUndoableEdit, DefaultStyledDocument.ElementBuffer, DefaultStyledDocument.ElementSpec, DefaultStyledDocument.SectionElement
-
Nested classes/interfaces declared in class javax.swing.text.AbstractDocument
AbstractDocument.AbstractElement, AbstractDocument.AttributeContext, AbstractDocument.BranchElement, AbstractDocument.Content, AbstractDocument.DefaultDocumentEvent, AbstractDocument.ElementEdit, AbstractDocument.LeafElement
-
-
Field Summary
Fields Modifier and Type Field Description static StringAdditionalCommentsDocument property key value.-
Fields declared in class javax.swing.text.DefaultStyledDocument
buffer, BUFFER_SIZE_DEFAULT
-
Fields declared in class javax.swing.text.AbstractDocument
BAD_LOCATION, BidiElementName, ContentElementName, ElementNameAttribute, listenerList, ParagraphElementName, SectionElementName
-
Fields declared in interface javax.swing.text.Document
StreamDescriptionProperty, TitleProperty
-
-
Constructor Summary
Constructors Constructor Description HTMLDocument()Constructs an HTML document using the default buffer size and a defaultStyleSheet.HTMLDocument(AbstractDocument.Content c, StyleSheet styles)Constructs an HTML document with the given content storage implementation and the given style/attribute storage mechanism.HTMLDocument(StyleSheet styles)Constructs an HTML document with the default content storage implementation and the specified style/attribute storage mechanism.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description protected voidcreate(DefaultStyledDocument.ElementSpec[] data)Replaces the contents of the document with the given element specifications.protected ElementcreateBranchElement(Element parent, AttributeSet a)Creates a document branch element, that can contain other elements.protected AbstractDocument.AbstractElementcreateDefaultRoot()Creates the root element to be used to represent the default document structure.protected ElementcreateLeafElement(Element parent, AttributeSet a, int p0, int p1)Creates a document leaf element that directly represents text (doesn't have any children).protected voidfireChangedUpdate(DocumentEvent e)Notifies all listeners that have registered interest for notification on this event type.protected voidfireUndoableEditUpdate(UndoableEditEvent e)Notifies all listeners that have registered interest for notification on this event type.URLgetBase()Returns the location to resolve relative URLs against.ElementgetElement(String id)Returns the element that has the given idAttribute.ElementgetElement(Element e, Object attribute, Object value)Returns the child element ofethat contains the attribute,attributewith valuevalue, ornullif one isn't found.HTMLDocument.IteratorgetIterator(HTML.Tag t)Fetches an iterator for the specified HTML tag.HTMLEditorKit.ParsergetParser()Returns the parser that is used when inserting HTML into the existing document.booleangetPreservesUnknownTags()Returns the behavior the parser observes when encountering unknown tags.HTMLEditorKit.ParserCallbackgetReader(int pos)Fetches the reader for the parser to use when loading the document with HTML.HTMLEditorKit.ParserCallbackgetReader(int pos, int popDepth, int pushDepth, HTML.Tag insertTag)Returns the reader for the parser to use to load the document with HTML.StyleSheetgetStyleSheet()Fetches theStyleSheetwith the document-specific display rules (CSS) that were specified in the HTML document itself.intgetTokenThreshold()Gets the number of tokens to buffer before trying to update the documents element structure.protected voidinsert(int offset, DefaultStyledDocument.ElementSpec[] data)Inserts new elements in bulk.voidinsertAfterEnd(Element elem, String htmlText)Inserts the HTML specified as a string after the end of the given element.voidinsertAfterStart(Element elem, String htmlText)Inserts the HTML specified as a string at the start of the element.voidinsertBeforeEnd(Element elem, String htmlText)Inserts the HTML specified as a string at the end of the element.voidinsertBeforeStart(Element elem, String htmlText)Inserts the HTML specified as a string before the start of the given element.protected voidinsertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr)Updates document structure as a result of text insertion.voidprocessHTMLFrameHyperlinkEvent(HTMLFrameHyperlinkEvent e)ProcessesHyperlinkEventsthat are generated by documents in an HTML frame.voidsetBase(URL u)Sets the location to resolve relative URLs against.voidsetInnerHTML(Element elem, String htmlText)Replaces the children of the given element with the contents specified as an HTML string.voidsetOuterHTML(Element elem, String htmlText)Replaces the given element in the parent with the contents specified as an HTML string.voidsetParagraphAttributes(int offset, int length, AttributeSet s, boolean replace)Sets attributes for a paragraph.voidsetParser(HTMLEditorKit.Parser parser)Sets the parser that is used by the methods that insert html into the existing document, such assetInnerHTML, andsetOuterHTML.voidsetPreservesUnknownTags(boolean preservesTags)Determines how unknown tags are handled by the parser.voidsetTokenThreshold(int n)Sets the number of tokens to buffer before trying to update the documents element structure.-
Methods declared in class javax.swing.text.DefaultStyledDocument
addDocumentListener, addStyle, getBackground, getCharacterElement, getDefaultRootElement, getFont, getForeground, getLogicalStyle, getParagraphElement, getStyle, getStyleNames, removeDocumentListener, removeElement, removeStyle, removeUpdate, setCharacterAttributes, setLogicalStyle, styleChanged
-
Methods declared in class javax.swing.text.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
-
Methods declared in class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
Methods declared in interface javax.swing.text.Document
addUndoableEditListener, createPosition, getEndPosition, getLength, getProperty, getRootElements, getStartPosition, getText, getText, insertString, putProperty, remove, removeUndoableEditListener, render
-
-
-
-
Field Detail
-
AdditionalComments
public static final String AdditionalComments
Document property key value. The value for the key will be a Vector of Strings that are comments not found in the body.- See Also:
- Constant Field Values
-
-
Constructor Detail
-
HTMLDocument
public HTMLDocument()
Constructs an HTML document using the default buffer size and a defaultStyleSheet. This is a convenience method for the constructorHTMLDocument(Content, StyleSheet).
-
HTMLDocument
public HTMLDocument(StyleSheet styles)
Constructs an HTML document with the default content storage implementation and the specified style/attribute storage mechanism. This is a convenience method for the constructorHTMLDocument(Content, StyleSheet).- Parameters:
styles- the styles
-
HTMLDocument
public HTMLDocument(AbstractDocument.Content c, StyleSheet styles)
Constructs an HTML document with the given content storage implementation and the given style/attribute storage mechanism.- Parameters:
c- the container for the contentstyles- the styles
-
-
Method Detail
-
getReader
public HTMLEditorKit.ParserCallback getReader(int pos)
Fetches the reader for the parser to use when loading the document with HTML. This is implemented to return an instance ofHTMLDocument.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)
Returns the reader for the parser to use to load the document with HTML. This is implemented to return an instance ofHTMLDocument.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 positionpopDepth- the number ofElementSpec.EndTagTypesto generate before insertingpushDepth- the number ofElementSpec.StartTagTypeswith a direction ofElementSpec.JoinNextDirectionthat should be generated before inserting, but after the end tags have been generatedinsertTag- 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 location to resolve relative URLs against. By default this will be the document's URL if the document was loaded from a URL. If a base tag is found and can be parsed, it will be used as the base location.- Returns:
- the base location
-
setBase
public void setBase(URL u)
Sets the location to resolve relative URLs against. By default this will be the document's URL if the document was loaded from a URL. If a base tag is found and can be parsed, it will be used as the base location.This also sets the base of the
StyleSheetto beuas well as the base of the document.- Parameters:
u- the desired base URL
-
insert
protected void insert(int offset, DefaultStyledDocument.ElementSpec[] data) throws BadLocationExceptionInserts new elements in bulk. This is how elements get created in the document. The parsing determines what structure is needed and creates the specification as a set of tokens that describe the edit while leaving the document free of a write-lock. This method can then be called in bursts by the reader to acquire a write-lock for a shorter duration (i.e. while the document is actually being altered).- Overrides:
insertin classDefaultStyledDocument- Parameters:
offset- the starting offsetdata- 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)
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:
insertUpdatein classDefaultStyledDocument- Parameters:
chng- a description of the document changeattr- the attributes
-
create
protected void create(DefaultStyledDocument.ElementSpec[] data)
Replaces the contents of the document with the given element specifications. This is called before insert if the loading is done in bursts. This is the only method called if loading the document entirely in one burst.- Overrides:
createin classDefaultStyledDocument- Parameters:
data- the new contents of the document
-
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:
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 attributesreplace- whether to replace existing attributes, or merge them
-
getStyleSheet
public StyleSheet getStyleSheet()
Fetches theStyleSheetwith 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)
Fetches an iterator for the specified HTML tag. This can be used for things like iterating over the set of anchors contained, or iterating over the input elements.- Parameters:
t- the requestedHTML.Tag- Returns:
- the
Iteratorfor the given HTML tag - See Also:
HTML.Tag
-
createLeafElement
protected Element createLeafElement(Element parent, AttributeSet a, int p0, int p1)
Creates a document leaf element that directly represents text (doesn't have any children). This is implemented to return an element of typeHTMLDocument.RunElement.- Overrides:
createLeafElementin classAbstractDocument- Parameters:
parent- the parent elementa- the attributes for the elementp0- 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)
Creates a document branch element, that can contain other elements. This is implemented to return an element of typeHTMLDocument.BlockElement.- Overrides:
createBranchElementin classAbstractDocument- Parameters:
parent- the parent elementa- the attributes- Returns:
- the element
-
createDefaultRoot
protected AbstractDocument.AbstractElement createDefaultRoot()
Creates the root element to be used to represent the default document structure.- Overrides:
createDefaultRootin classDefaultStyledDocument- Returns:
- the element base
-
setTokenThreshold
public void setTokenThreshold(int n)
Sets the number of tokens to buffer before trying to update the documents element structure.- Parameters:
n- the number of tokens to buffer
-
getTokenThreshold
public int getTokenThreshold()
Gets the number of tokens to buffer before trying to update the documents element structure. The default value isInteger.MAX_VALUE.- Returns:
- the number of tokens to buffer
-
setPreservesUnknownTags
public void setPreservesUnknownTags(boolean preservesTags)
Determines how unknown tags are handled by the parser. If set to true, unknown tags are put in the model, otherwise they are dropped.- Parameters:
preservesTags- true if unknown tags should be saved in the model, otherwise tags are dropped- See Also:
HTML.Tag
-
getPreservesUnknownTags
public boolean getPreservesUnknownTags()
Returns the behavior the parser observes when encountering unknown tags.- Returns:
- true if unknown tags are to be preserved when parsing
- See Also:
HTML.Tag
-
processHTMLFrameHyperlinkEvent
public void processHTMLFrameHyperlinkEvent(HTMLFrameHyperlinkEvent e)
ProcessesHyperlinkEventsthat are generated by documents in an HTML frame. TheHyperlinkEventtype, as the parameter suggests, isHTMLFrameHyperlinkEvent. In addition to the typical information contained in aHyperlinkEvent, 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.SRCattribute and fires aChangedUpdateevent.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.SRCattribute to have a value equal to the destination URL and fire aRemovedUpdateandInsertUpdate.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.SRCattribute is updated and aChangedUpdateevent is fired.- Parameters:
e- the event
-
setParser
public void setParser(HTMLEditorKit.Parser parser)
Sets the parser that is used by the methods that insert html into the existing document, such assetInnerHTML, andsetOuterHTML.HTMLEditorKit.createDefaultDocumentwill set the parser for you. If you create anHTMLDocumentby 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 that is used when inserting HTML into the existing document.- Returns:
- the parser used for text insertion
- Since:
- 1.3
-
setInnerHTML
public void setInnerHTML(Element elem, String htmlText) throws BadLocationException, IOException
Replaces the children of the given element with the contents specified as an HTML string.This will be seen as at least two events, n inserts followed by a remove.
Consider the following structure (the
elemparameter 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
elemmust not be a leaf element, otherwise anIllegalArgumentExceptionis thrown. If eitherelemorhtmlTextparameter isnull, no changes are made to the document.For this to work correctly, the document must have an
HTMLEditorKit.Parserset. This will be the case if the document was created from an HTMLEditorKit via thecreateDefaultDocumentmethod.- Parameters:
elem- the branch element whose children will be replacedhtmlText- the string to be parsed and assigned toelem- Throws:
IllegalArgumentException- ifelemis a leafIllegalStateException- if anHTMLEditorKit.Parserhas not been definedBadLocationException- if replacement is impossible because of a structural issueIOException- if an I/O exception occurs- Since:
- 1.3
-
setOuterHTML
public void setOuterHTML(Element elem, String htmlText) throws BadLocationException, IOException
Replaces the given element in the parent with the contents specified as an HTML string.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
elemparameter 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
elemorhtmlTextparameter isnull, 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
createDefaultDocumentmethod.- Parameters:
elem- the element to replacehtmlText- the string to be parsed and inserted in place ofelem- Throws:
IllegalStateException- if an HTMLEditorKit.Parser has not been setBadLocationException- if replacement is impossible because of a structural issueIOException- if an I/O exception occurs- Since:
- 1.3
-
insertAfterStart
public void insertAfterStart(Element elem, String htmlText) throws BadLocationException, IOException
Inserts the HTML specified as a string at the start of the element.Consider the following structure (the
elemparameter 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
insertBeforeStartmethod, new elements become children of the specified element, not siblings.Parameter
elemmust not be a leaf element, otherwise anIllegalArgumentExceptionis thrown. If eitherelemorhtmlTextparameter isnull, no changes are made to the document.For this to work correctly, the document must have an
HTMLEditorKit.Parserset. This will be the case if the document was created from an HTMLEditorKit via thecreateDefaultDocumentmethod.- Parameters:
elem- the branch element to be the root for the new texthtmlText- the string to be parsed and assigned toelem- Throws:
IllegalArgumentException- ifelemis a leafIllegalStateException- if an HTMLEditorKit.Parser has not been set on the documentBadLocationException- if insertion is impossible because of a structural issueIOException- if an I/O exception occurs- Since:
- 1.3
-
insertBeforeEnd
public void insertBeforeEnd(Element elem, String htmlText) throws BadLocationException, IOException
Inserts the HTML specified as a string at the end of the element.If
elem's children are leaves, and the character at aelem.getEndOffset() - 1is a newline, this will insert before the newline so that there isn't text after the newline.Consider the following structure (the
elemparameter 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
insertAfterEndmethod, new elements become children of the specified element, not siblings.Parameter
elemmust not be a leaf element, otherwise anIllegalArgumentExceptionis thrown. If eitherelemorhtmlTextparameter isnull, no changes are made to the document.For this to work correctly, the document must have an
HTMLEditorKit.Parserset. This will be the case if the document was created from an HTMLEditorKit via thecreateDefaultDocumentmethod.- Parameters:
elem- the element to be the root for the new texthtmlText- the string to be parsed and assigned toelem- Throws:
IllegalArgumentException- ifelemis a leafIllegalStateException- if an HTMLEditorKit.Parser has not been set on the documentBadLocationException- if insertion is impossible because of a structural issueIOException- if an I/O exception occurs- Since:
- 1.3
-
insertBeforeStart
public void insertBeforeStart(Element elem, String htmlText) throws BadLocationException, IOException
Inserts the HTML specified as a string before the start of the given element.Consider the following structure (the
elemparameter 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
insertAfterStartmethod, new elements become siblings of the specified element, not children.If either
elemorhtmlTextparameter isnull, no changes are made to the document.For this to work correctly, the document must have an
HTMLEditorKit.Parserset. This will be the case if the document was created from an HTMLEditorKit via thecreateDefaultDocumentmethod.- Parameters:
elem- the element the content is inserted beforehtmlText- the string to be parsed and inserted beforeelem- Throws:
IllegalStateException- if an HTMLEditorKit.Parser has not been set on the documentBadLocationException- if insertion is impossible because of a structural issueIOException- if an I/O exception occurs- Since:
- 1.3
-
insertAfterEnd
public void insertAfterEnd(Element elem, String htmlText) throws BadLocationException, IOException
Inserts the HTML specified as a string after the end of the given element.Consider the following structure (the
elemparameter 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
insertBeforeEndmethod, new elements become siblings of the specified element, not children.If either
elemorhtmlTextparameter isnull, no changes are made to the document.For this to work correctly, the document must have an
HTMLEditorKit.Parserset. This will be the case if the document was created from an HTMLEditorKit via thecreateDefaultDocumentmethod.- Parameters:
elem- the element the content is inserted afterhtmlText- the string to be parsed and inserted afterelem- Throws:
IllegalStateException- if an HTMLEditorKit.Parser has not been set on the documentBadLocationException- if insertion is impossible because of a structural issueIOException- if an I/O exception occurs- Since:
- 1.3
-
getElement
public Element getElement(String id)
Returns the element that has the given idAttribute. If the element can't be found,nullis returned. Note that this method works on anAttribute, 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 forgetElement(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:
HTML.Attribute
-
getElement
public Element getElement(Element e, Object attribute, Object value)
Returns the child element ofethat contains the attribute,attributewith valuevalue, ornullif one isn't found. This is not thread-safe.- Parameters:
e- the root element where the search beginsattribute- the desiredAttributevalue- 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:
HTML.Attribute
-
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.- Overrides:
fireChangedUpdatein classAbstractDocument- 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.- Overrides:
fireUndoableEditUpdatein classAbstractDocument- Parameters:
e- the event- See Also:
EventListenerList
-
-