本文目录导读:

看起来您遇到了 JEditorPane 在使用 HTMLEditorKit 解析 HTML 时出现的"关闭选择器"相关错误,这是一个典型的 Java Swing HTML 解析问题。
问题原因
这个问题通常发生在以下几种情况:
- HTML 标签未正确闭合
- CSS 选择器语法错误
- HTML 解析器版本兼容性问题
解决方案
检查 HTML 格式
确保 HTML 标签正确闭合:
// ❌ 错误示例 String html = "<div><p>文本</div>"; // ✅ 正确示例 String html = "<div><p>文本</p></div>";
使用正确的 HTML 设置
JEditorPane editorPane = new JEditorPane();
editorPane.setContentType("text/html");
editorPane.setEditable(false);
// 使用基本 HTML(避免复杂 CSS)
String html = "<html><body>"
+ "<h1>标题</h1>"
+ "<p>段落内容</p>"
+ "</body></html>";
editorPane.setText(html);
自定义 HTMLEditorKit
import javax.swing.*;
import javax.swing.text.html.*;
import javax.swing.text.*;
public class CustomHTMLEditorKit extends HTMLEditorKit {
@Override
public Document createDefaultDocument() {
HTMLDocument doc = (HTMLDocument) super.createDefaultDocument();
// 设置解析器不严格检查
doc.setAsynchronousLoadPriority(-1);
return doc;
}
}
// 使用方式
JEditorPane editorPane = new JEditorPane();
editorPane.setEditorKit(new CustomHTMLEditorKit());
HTML 清理工具
public class HTMLSanitizer {
public static String sanitize(String html) {
// 移除可能引起问题的 CSS
html = html.replaceAll("<style[^>]*>[^<]*</style>", "");
// 确保基本标签闭合
html = html.replaceAll("<br>", "<br/>");
html = html.replaceAll("<img([^>]*)>", "<img$1/>");
// 添加基本结构
if (!html.startsWith("<html>")) {
html = "<html><body>" + html + "</body></html>";
}
return html;
}
}
// 使用
String cleanedHTML = HTMLSanitizer.sanitize(yourHTMLString);
editorPane.setText(cleanedHTML);
错误处理
try {
editorPane.setText(html);
} catch (Exception e) {
System.err.println("HTML 解析错误: " + e.getMessage());
// 降级处理
editorPane.setText("<html><body><p>内容显示错误</p></body></html>");
}
完整示例
import javax.swing.*;
import javax.swing.text.html.*;
import java.awt.*;
public class HTMLViewer extends JFrame {
private JEditorPane editorPane;
public HTMLViewer() {
setTitle("HTML Viewer");
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
editorPane = new JEditorPane();
editorPane.setContentType("text/html");
editorPane.setEditable(false);
// 安全的 HTML 内容
String safeHTML = createSafeHTML();
editorPane.setText(safeHTML);
JScrollPane scrollPane = new JScrollPane(editorPane);
add(scrollPane, BorderLayout.CENTER);
setVisible(true);
}
private String createSafeHTML() {
return "<html><body style='font-family: Arial; font-size: 12pt;'>"
+ "<h2>标题</h2>"
+ "<p>这是一个 <b>测试</b> 页面</p>"
+ "<ul>"
+ "<li>项目 1</li>"
+ "<li>项目 2</li>"
+ "</ul>"
+ "</body></html>";
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new HTMLViewer());
}
}
建议
- 避免复杂 CSS:JEditorPane 的 HTML 解析器对 CSS 支持有限
- 使用简单 HTML:仅使用基本的 HTML 标签预处理**:在显示前清理 HTML 内容
- 考虑替代方案:如需复杂 HTML 渲染,考虑使用 JavaFX WebView
如果问题仍然存在,请提供具体的 HTML 内容或错误堆栈信息,以便更精确地定位问题。