在JTextPane中使用HTML时,如何获取原始输入的HTML内容?
问题描述
使用JTextPane的HTML模式插入文本,代码如下:
JTextPane textPane = new JTextPane(); textPane.setContentType("text/html"); String text = "Some <b>html</b> text..."; HTMLDocument doc = (HTMLDocument) textPane.getDocument(); HTMLEditorKit editorKit = (HTMLEditorKit) textPane.getEditorKit(); try { doc.remove(0, doc.getLength()); editorKit.insertHTML(doc, 0, text, 0, 0, null); } catch (BadLocationException e) { e.printStackTrace(); } catch (IOException e) { throw new RuntimeException(e); }
希望能获取到与输入完全一致的文本,实现如下效果:
String returnedText = textPane.getText(); // 或其他方法 if ( text.equals(returnedText) ) { System.out.println("I want this to be executed"); }
请问是否可行?有没有相关方法或类实现?还是输入的文本总会被修改,无法还原原始内容?
回答
直接通过JTextPane的默认方法无法获取和输入完全一致的原始HTML文本,原因是HTMLEditorKit与HTMLDocument在处理HTML时会自动做标准化处理:比如补全闭合标签、调整标签格式、转义特殊字符等,导致输出内容和原始输入存在差异。
可行的解决方案分为两种:
缓存原始输入文本(最可靠)
不需要从JTextPane中反向提取,直接将输入的text字符串存储为变量(比如类的成员变量),后续需要对比或使用时直接调用这个缓存值即可。示例:// 缓存原始HTML文本 String originalHtml = "Some <b>html</b> text..."; // 插入到JTextPane的代码不变... // 需要对比时直接用缓存的字符串 if (originalHtml.equals(targetText)) { System.out.println("I want this to be executed"); }自定义HTMLWriter控制输出格式(仅能近似还原)
如果必须从JTextPane的文档中获取HTML内容,可以自定义HTMLEditorKit.HTMLWriter,重写相关方法来减少标准化处理,尽可能贴近原始输入。但这种方式无法100%还原原始文本,因为文档内部已经完成了标准化转换。示例:public static String getHtmlFromTextPane(JTextPane textPane) throws IOException, BadLocationException { HTMLDocument doc = (HTMLDocument) textPane.getDocument(); HTMLEditorKit kit = (HTMLEditorKit) textPane.getEditorKit(); StringWriter writer = new StringWriter(); // 使用自定义HTMLWriter调整输出逻辑 HTMLEditorKit.HTMLWriter htmlWriter = new HTMLEditorKit.HTMLWriter(writer, doc) { @Override protected void startTag(HTML.Tag tag, MutableAttributeSet attr) throws IOException { // 示例:避免自动添加不必要的属性或格式化 super.startTag(tag, attr); } }; htmlWriter.write(); return writer.toString(); }
另外需要注意:textPane.getText()在HTML模式下返回的是去除HTML标签后的纯文本内容,并非原始HTML源码,所以肯定无法和输入的HTML字符串匹配。
内容的提问来源于stack exchange,提问作者Jason
相关产品推荐
相关产品推荐

