本文目录导读:

看起来你遇到了 JEditorPane 配合 HTMLEditorKit 解析 HTML 时出现的异常,这个问题通常发生在 Java Swing 的 HTML 渲染组件中,当解析器遇到不标准或格式错误的 HTML 内容时抛出。
常见异常场景
这个异常通常表现为类似:
javax.swing.text.html.HTMLEditorKit$ParserCallback 或
java.lang.Throwable 在 HTML 解析过程中被抛出
主要解决方案
捕获并忽略异常
JEditorPane editor = new JEditorPane();
editor.setContentType("text/html");
try {
editor.setText(htmlContent);
} catch (RuntimeException e) {
// 忽略 HTML 解析异常
System.err.println("HTML 解析警告: " + e.getMessage());
// 设置纯文本作为 fallback
editor.setText(stripHtml(htmlContent));
}
使用自定义 HTMLEditorKit
import javax.swing.text.html.*;
import javax.swing.text.*;
public class LenientHtmlEditorKit extends HTMLEditorKit {
@Override
public Document createDefaultDocument() {
HTMLDocument doc = new HTMLDocument() {
@Override
public void setInnerHTML(Element elem, String htmlText) {
try {
super.setInnerHTML(elem, htmlText);
} catch (Exception e) {
// 忽略异常
}
}
};
return doc;
}
}
// 使用方式
JEditorPane editor = new JEditorPane();
editor.setEditorKit(new LenientHtmlEditorKit());
editor.setText(htmlContent);
预处理 HTML 内容
private String sanitizeHtml(String html) {
// 移除可能导致问题的元素
html = html.replaceAll("<script[^>]*>[\\s\\S]*?</script>", "");
html = html.replaceAll("<style[^>]*>[\\s\\S]*?</style>", "");
// 修复不完整的标签
html = html.replaceAll("<br>", "<br/>");
html = html.replaceAll("<hr>", "<hr/>");
// 确保是有效的 HTML 片段
if (!html.startsWith("<html>")) {
html = "<html><body>" + html + "</body></html>";
}
return html;
}
使用 SwingWorker 异步加载
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
try {
editorPane.setText(htmlContent);
} catch (Exception e) {
// 记录异常但不中断
}
return null;
}
};
worker.execute();
根本原因排查
- 检查 HTML 格式:确保 HTML 是有效的 XHTML 格式
- 版本兼容性:Java 不同版本对 HTML 解析的支持不同
- 内存问题:大量 HTML 内容可能导致解析异常
建议的最佳实践
public class SafeHtmlEditor extends JEditorPane {
public SafeHtmlEditor() {
super();
setContentType("text/html");
// 设置更大的编辑 Kit 以处理复杂 HTML
setEditorKit(new HTMLEditorKit() {
@Override
public ViewFactory getViewFactory() {
return new HTMLFactory() {
@Override
public View create(Element elem) {
try {
return super.create(elem);
} catch (Exception e) {
return new javax.swing.text.html.InlineView(elem);
}
}
};
}
});
}
}
如果你能提供更具体的异常堆栈信息或代码上下文,我可以给出更针对性的解决方案。