本文目录导读:

这个错误信息看起来是 Java Swing 中 JEditorPane 使用 HTMLEditorKit 解析 HTML 时出现的内部错误。"NoConnectionPending" 这个短语通常与 NIO (Non-blocking I/O) 的 SocketChannel 有关,但在 Swing 的 HTML 渲染中出现,通常意味着以下几种情况:
主要原因
HTML 内容中包含需要联网加载的资源,但网络连接失败
最常见的原因是 JEditorPane 加载的 HTML 中引用了外部资源(如 CSS、图片、iframe),而解析器在尝试建立连接时失败。
HTML 语法问题或解析器 bug
某些不标准的 HTML 结构会触发解析器内部异常。
HTMLEditorKit 与 JRE 版本的兼容性问题
较旧的 Java 版本(如 Java 8 某些更新)存在已知的 HTML 解析 bug。
解决方案
方案 1:禁用外部资源加载(推荐)
JEditorPane editor = new JEditorPane();
editor.setContentType("text/html");
editor.setEditable(false);
editor.getDocument().putProperty("IgnoreCharsetDirective", Boolean.TRUE);
// 设置 HTMLEditorKit 的默认样式表为空,避免加载外部资源
HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit();
StyleSheet styleSheet = kit.getStyleSheet();
styleSheet.addRule("body { }"); // 空规则覆盖默认
方案 2:使用自定义 HTMLEditorKit 捕获异常
class SafeHTMLEditorKit extends HTMLEditorKit {
@Override
public Document createDefaultDocument() {
HTMLDocument doc = (HTMLDocument) super.createDefaultDocument();
doc.setAsynchronousLoadPriority(-1); // 禁用异步加载
return doc;
}
}
// 使用
JEditorPane editor = new JEditorPane();
editor.setEditorKit(new SafeHTMLEditorKit());
editor.setText("<html><body>你的内容</body></html>");
方案 3:升级 Java 版本
如果使用 Java 8,尝试升级到 Java 11+,该问题在后续版本中得到修复。
方案 4:完全避免使用 JEditorPane(强烈推荐)
JEditorPane 的 HTML 渲染能力非常有限,建议使用:
- JavaFX WebView(如果允许使用 JavaFX)
- JTextPane + 手动解析(简单文本)
- 第三方库如 Flyingsaucer(XHTML/CSS 渲染)
代码示例(完整修复版)
import javax.swing.*;
import javax.swing.text.html.*;
import java.awt.*;
public class SafeHtmlViewer {
public static void main(String[] args) {
JFrame frame = new JFrame();
JEditorPane editor = new JEditorPane();
editor.setContentType("text/html");
editor.setEditable(false);
// 关键:禁用异步加载
((HTMLDocument)editor.getDocument()).setAsynchronousLoadPriority(-1);
String html = "<html><body>测试内容</body></html>";
try {
editor.setText(html);
} catch (Exception e) {
// 如果仍然出错,使用更安全的设置
HTMLEditorKit kit = new HTMLEditorKit();
HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
doc.setAsynchronousLoadPriority(-1);
doc.setParser(new ParserDelegator() {
// 覆盖解析器
});
editor.setEditorKit(kit);
editor.setDocument(doc);
editor.setText(html);
}
frame.add(new JScrollPane(editor));
frame.setSize(400, 300);
frame.setVisible(true);
}
}
排查步骤
- 检查 HTML 内容:去掉所有外部引用(
<img src="http://...">、<link>等) - 简化测试:只放纯文本
<html><body>Hello</body></html> - 日志检查:在调用
setText()或setPage()时添加 try-catch
最可靠的解决方案是 禁用所有异步和网络相关功能,因为 JEditorPane 的设计在 Swing 中已经是遗留组件。
如果问题持续,强烈建议迁移到 JavaFX 的 WebView 或 第三方 HTML 渲染库。