Reputation: 9121
I am using a JTextPane
to print out chat messages, implementation:
private HTMLEditorKit kit;
private HTMLDocument doc;
ta = new JTextPane();
ta.setEditable(false);
ta.setContentType("text/html");
sbrText = new JScrollPane(ta);
sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
sbrText.setBorder(null);
doc = (HTMLDocument)ta.getDocument();
kit = (HTMLEditorKit)ta.getEditorKit();
The messages are being inserted like this:
try {
kit.insertHTML(doc, doc.getLength(), "<div style=\"padding-top:10px;
padding-bottom:10px;\" id=\"X\">" + "<div>" + from + " at
" + tid + ":</div>" + "<div style=\"padding-top:4px;" +
align + "\">" + msg + "</div>" + "</div>", 0, 0, null);
} catch (BadLocationException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
Each message (div) gets a unique ID, i want to select a certain ID and update the contents of that html insert.
Is this possible?
Upvotes: 1
Views: 547
Reputation: 1158
Since each DIV has a unique ID, you can use the getElement
method from the HTMLDocument
class to fetch exactly the DIV in question. Thus, you don't need to traverse the whole DOM scanning for elements with an ID attribute and comparing IDs.
Although setOuterHTML
allows you to replace the contents of a given element, it also replaces the element itself. What you need instead is setInnerHTML
which, as it name suggests, leaves the containing tags untouched.
All in all, the code for what you are trying to do would go along the following lines:
public void replaceContents (String sID, String sContents) {
try {
doc.setInnerHTML (doc.getElement (sID), sContents);
} catch (BadLocationException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
Hope that helps!
Upvotes: 0
Reputation: 57381
It's possible. You can get the document from the JTextPane
and use getDefaultRootElement()
to get root of the DOM. Then go through all the childrent and children of children Elements. For each of them use getAttributes()
and check whether there is ID attribute. Then check the attribute value.
When you achieve Element
with specified ID use HTMLDocument
's method
public void setOuterHTML(Element elem, String htmlText)
Upvotes: 4