本文目录导读:

JEditorPane 是 Java Swing 中的一个组件,但它不支持像 Word 或现代富文本编辑器(如 TinyMCE、CKEditor)那样的完整富文本编辑功能(如字体颜色、字号、图片插入等)。
JEditorPane 主要用于显示和编辑简单的 HTML(HTML 3.2)和 RTF(富文本格式)内容,它的富文本能力非常有限,且不支持 CSS 样式表或现代 HTML 特性。
JEditorPane 富文本编辑的核心能力
你只能用它来:
- 编辑文本内容:插入、删除字符。
- 应用有限的属性:通过
StyledDocument或HTMLEditorKit设置加粗、斜体、下划线。 - 设置颜色:可以设置文本色
setForeground、背景色setBackground。 - 设置字体:字体名称、大小、样式。
- 使用段落属性:对齐(左、中、右),缩进,行距等。
它不能做:插入图片、表格、超链接(虽然可以显示,但编辑麻烦)、使用 CSS、动态加载外部图片等。
实现简单的富文本编辑器示例
下面是一个完整的 Java Swing 程序,展示如何使用 JEditorPane 实现一个最基本的富文本编辑器(仅支持加粗、斜体、下划线、颜色、字体大小)。
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleRichTextEditor extends JFrame {
private JEditorPane editor;
private StyledDocument doc;
public SimpleRichTextEditor() {
setTitle("JEditorPane 简单富文本编辑");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
setLocationRelativeTo(null);
// 初始化编辑器
editor = new JEditorPane();
editor.setContentType("text/html"); // 使用 HTML 模式
editor.setEditable(true);
doc = (StyledDocument) editor.getDocument();
// 设置初始内容
editor.setText("<html><body><p style='font-family:Arial; font-size:14px;'>这是一个 JEditorPane 富文本编辑示例。</p></body></html>");
// 滚动面板
JScrollPane scrollPane = new JScrollPane(editor);
add(scrollPane, BorderLayout.CENTER);
// 工具栏
JToolBar toolbar = new JToolBar();
add(toolbar, BorderLayout.NORTH);
// 加粗按钮
JButton boldBtn = new JButton("B");
boldBtn.setFont(boldBtn.getFont().deriveFont(Font.BOLD));
boldBtn.addActionListener(e -> toggleAttribute(StyleConstants.Bold));
toolbar.add(boldBtn);
// 斜体按钮
JButton italicBtn = new JButton("I");
italicBtn.setFont(italicBtn.getFont().deriveFont(Font.ITALIC));
italicBtn.addActionListener(e -> toggleAttribute(StyleConstants.Italic));
toolbar.add(italicBtn);
// 下划线按钮
JButton underlineBtn = new JButton("U");
underlineBtn.setFont(underlineBtn.getFont().deriveFont(PlainView.class.getName() != null ? Font.PLAIN : Font.PLAIN));
underlineBtn.addActionListener(e -> toggleAttribute(StyleConstants.Underline));
toolbar.add(underlineBtn);
toolbar.addSeparator();
// 字体大小选择
String[] sizes = {"12", "14", "16", "18", "20", "24", "30"};
JComboBox<String> sizeCombo = new JComboBox<>(sizes);
sizeCombo.setEditable(true);
sizeCombo.addActionListener(e -> {
try {
int size = Integer.parseInt((String) sizeCombo.getSelectedItem());
setAttribute(StyleConstants.FontSize, size);
} catch (NumberFormatException ex) {
// ignore
}
});
toolbar.add(new JLabel("字号:"));
toolbar.add(sizeCombo);
toolbar.addSeparator();
// 颜色选择按钮
JButton colorBtn = new JButton("颜色");
colorBtn.addActionListener(e -> {
Color color = JColorChooser.showDialog(this, "选择颜色", Color.BLACK);
if (color != null) {
setAttribute(StyleConstants.Foreground, color);
}
});
toolbar.add(colorBtn);
// 模板方法:切换布尔属性
private void toggleAttribute(Object attribute) {
int start = editor.getSelectionStart();
int end = editor.getSelectionEnd();
if (start == end) return;
// 获取当前属性
Element element = doc.getCharacterElement(start);
AttributeSet as = element.getAttributes();
boolean current = false;
if (attribute == StyleConstants.Bold) {
current = StyleConstants.isBold(as);
} else if (attribute == StyleConstants.Italic) {
current = StyleConstants.isItalic(as);
} else if (attribute == StyleConstants.Underline) {
current = StyleConstants.isUnderline(as);
}
// 设置反转后的值
setAttribute(attribute, !current);
}
// 模板方法:设置属性
private void setAttribute(Object attribute, Object value) {
int start = editor.getSelectionStart();
int end = editor.getSelectionEnd();
if (start == end) return;
// 使用 MutableAttributeSet
MutableAttributeSet attrs = new SimpleAttributeSet();
if (attribute == StyleConstants.Bold) {
StyleConstants.setBold(attrs, (Boolean) value);
} else if (attribute == StyleConstants.Italic) {
StyleConstants.setItalic(attrs, (Boolean) value);
} else if (attribute == StyleConstants.Underline) {
StyleConstants.setUnderline(attrs, (Boolean) value);
} else if (attribute == StyleConstants.FontSize) {
StyleConstants.setFontSize(attrs, (Integer) value);
} else if (attribute == StyleConstants.Foreground) {
StyleConstants.setForeground(attrs, (Color) value);
}
doc.setCharacterAttributes(start, end - start, attrs, false);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new SimpleRichTextEditor().setVisible(true);
});
}
}
为什么你不应该用 JEditorPane 做复杂富文本编辑
| 问题 | 说明 |
|---|---|
| HTML 支持极差 | 只支持 HTML 3.2,不支持 CSS、<div>、<span>、<table> 等现代元素 |
| 图片不支持 | 不能编辑图片,只能通过 setIcon 显示(且不能插入) |
| 无法实现撤销/重做 | 没有内置的 UndoManager 支持(需要自己实现) |
| 性能差 | 处理大量文本或复杂样式时非常慢 |
| 跨平台问题 | 在不同操作系统上渲染效果不一致 |
| 缺乏现代编辑功能 | 没有拼写检查、自动换行、拖拽、剪切板等 |
推荐替代方案(如果你需要真正的富文本编辑器)
-
JavaFX WebView + TinyMCE/Quill
使用 JavaFX 的WebView加载一个嵌入式 Web 富文本编辑器(如 TinyMCE、Quill、CKEditor),通过 Java 与 JavaScript 通信获取 HTML 内容,这是目前最成熟的方式。 -
独立富文本编辑器库
- RichTextFX(推荐):基于 JavaFX 的富文本编辑器,支持图片、表格、样式等,功能强大。
- JTextPane:比 JEditorPane 稍好一点,但本质相同,不推荐。
- RSyntaxTextArea:专为代码编辑器设计,不支持富文本。
-
嵌入 WebView 示例(JavaFX)
WebView webView = new WebView(); WebEngine engine = webView.getEngine(); engine.loadContent("<html><body><div id='editor'>Hello</div></body></html>"); // 注入富文本编辑器脚本(如 TinyMCE) // 通过 JS 回调获取内容
- JEditorPane:适合显示简单的 HTML 或 RTF,或编辑极其简单的样式(粗体、斜体、颜色)。
- 如果你需要:插入图片、表格、字体颜色、字号、撤销/重做、导出为 Word/PDF → 不要用 JEditorPane,直接使用 RichTextFX 或 JavaFX WebView + 现代 Web 富文本编辑器。