|
|
||
Sergey Groznyh's Blog
«Removing elements from Swing HTMLDocument |
Main
| Generating Print Preview of Swing Text Components »
Removing elements from Swing HTML in JDK6Posted by g_s_m on August 01, 2007 at 10:12 AM | Comments (0)After I published the entry on removing elements from Swing HTMLDocument in JDK7, I got a question from a reader: but how to actually remove elements in JDK6? There's no easy way, but what is the hard way? Well, there exist a bunch of methods, to various degrees of ugliness, let's look at one of them. It's neither pretty nor effective, but has the advantage of being simple enough. The method is to serialize all the sibling elements
using The following code illustrates this approach.
void removeElement(HTMLDocument d, Element e) throws Exception {
Element p = e.getParentElement();
int n = p.getElementCount();
String s = "";
for (int i = 0; i < n; i++) {
Element c = p.getElement(i);
if (c != e) {
s += getElementText(d, c);
}
}
d.setInnerHTML(p, s);
}
The tricky thing is, how to serialize not the complete document but
a single element only. There exist a constructor in
the To overcome this, we need to override
the
String getElementText(HTMLDocument d, final Element e) throws Exception {
StringWriter sw = new StringWriter();
int p0 = e.getStartOffset();
int p1 = e.getEndOffset();
new HTMLWriter(sw, d, p0, p1 - p0) {
protected ElementIterator getElementIterator() {
return new ElementIterator(e);
}
}.write();
return sw.toString();
}
Note that if we try to remove the sole child element, the behavior
of this method differs from Bookmark blog post: CommentsComments are listed in date ascending order (oldest first) | Post Comment | ||
|
|