本文目录导读:

这个错误通常发生在使用 JEditorPane 和 HTMLEditorKit 解析 HTML 内容时,遇到了字符串索引超出范围的问题,以下是一些常见原因和解决方案:
常见原因
- 不完整或格式错误的 HTML - 标签未闭合或结构损坏
- 特殊字符未转义 - 如
&、<、>等 - 编码问题 - HTML 内容包含无法处理的字符
- - 设置了空的或 null 的 HTML 内容
解决方案
验证 HTML 内容
// 确保 HTML 内容完整 String html = "<html><body>" + content + "</body></html>"; editorPane.setText(html);
转义特殊字符
import org.apache.commons.lang3.StringEscapeUtils;
String safeHtml = StringEscapeUtils.escapeHtml4(originalContent);
editorPane.setText("<html><body>" + safeHtml + "</body></html>");
使用 try-catch 处理异常
try {
editorPane.setText(htmlContent);
} catch (Exception e) {
System.err.println("HTML parsing error: " + e.getMessage());
// 使用普通文本显示
editorPane.setContentType("text/plain");
editorPane.setText("Error displaying HTML content");
}
设置默认的 HTML 内容
// 先设置一个空文档
editorPane.setContentType("text/html");
editorPane.setText("<html><body></body></html>");
// 然后再设置实际内容
editorPane.setText(htmlContent);
使用 DocumentFilter 或自定义解析
// 创建自定义的 HTMLEditorKit
HTMLEditorKit kit = new HTMLEditorKit() {
@Override
public Document createDefaultDocument() {
HTMLDocument doc = (HTMLDocument) super.createDefaultDocument();
// 设置解析器属性
doc.setAsynchronousLoadPriority(-1);
return doc;
}
};
editorPane.setEditorKit(kit);
调试建议
-
打印出有问题的 HTML 内容:
System.out.println("HTML length: " + htmlContent.length()); System.out.println("First 100 chars: " + htmlContent.substring(0, Math.min(100, htmlContent.length()))); -
使用简单的 HTML 测试:
// 测试简单的 HTML editorPane.setText("<html><body><p>Test</p></body></html>"); -
检查特殊字符:
// 替换可能的特殊字符 String safeContent = htmlContent .replace("&", "&") .replace("<", "<") .replace(">", ">");
完整的解决方案示例
public class SafeHtmlEditor {
public static void setHtmlContent(JEditorPane editorPane, String html) {
try {
// 确保 HTML 完整
if (!html.toLowerCase().startsWith("<html")) {
html = "<html><body>" + html + "</body></html>";
}
// 设置内容类型
editorPane.setContentType("text/html");
// 清除现有内容
editorPane.setText("");
// 设置新内容
editorPane.setText(html);
} catch (Exception e) {
// 异常时使用纯文本
editorPane.setContentType("text/plain");
editorPane.setText("Error: " + e.getMessage());
}
}
}
如果问题仍然存在,建议检查生成 HTML 内容的代码,确保没有生成格式错误的标记。