Problem: The content of the leaf nodes of my tree is HTML, but I don't want them rendered as HTML.
Many Swing components can include snippets of HTML in order to change how they are rendered. This includes the nodes of a JTree
:
DefaultMutableTreeNode myLeafNode = new DefaultMutableTreeNode("<html><body><h1>Hello World</h1></body></html>");
If this node is added to the DefaultTreeModel
, and the model to the JTree
, it will render the content as HTML.
How do I prevent this? How do I force it to be rendered as plain text?
Edit: @David Wallace's answer (see below) works. Here's how it looks:
Use the StringEscapeUtils
class from the Apache Commons library, to escape your HTML, then put it inside <html><body>
to tell Swing to display the result as HTML.
import org.apache.commons.lang3.StringEscapeUtils;
String escapedHtml = StringEscapeUtils.escapeHtml4(htmlToDisplay);
DefaultMutableTreeNode myLeafNode =
new DefaultMutableTreeNode("<html><body>" + escapedHtml + "</body></html>");