简体   繁体   English

如何在JTree中将纯文本显示为HTML?

[英]How do I display HTML as plain text in a JTree?

Problem : The content of the leaf nodes of my tree is HTML, but I don't want them rendered as HTML. 问题 :我树的叶节点的内容是HTML,但我不希望它们呈现为HTML。

Many Swing components can include snippets of HTML in order to change how they are rendered. 许多Swing组件可以包含HTML的片段,以便更改它们的呈现方式。 This includes the nodes of a JTree : 这包括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. 如果将此节点添加到DefaultTreeModel ,并将模型添加到JTree ,则会将内容呈现为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. 编辑 :@David Wallace的答案(见下文)有效。 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. 使用Apache Commons库中的StringEscapeUtils类来转义HTML,然后将其放在<html><body> ,告诉Swing将结果显示为HTML。

import org.apache.commons.lang3.StringEscapeUtils;

String escapedHtml = StringEscapeUtils.escapeHtml4(htmlToDisplay); 
DefaultMutableTreeNode myLeafNode = 
    new DefaultMutableTreeNode("<html><body>" + escapedHtml + "</body></html>");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM