我正在尝试实现一个小的 HTML 编辑器,它允许将前景色和背景色应用于部分文本。我想以 HTML 格式存储文本,并将着色信息保存在文件中。我当前的实现在使用不同样式编辑文本时正常运行(样式定义前景色和背景色信息)。但是,当将编辑后的文档存储在文件中时,我得到了不正确的结构化 HTML,并且使用特定样式输入的文本部分丢失了。这是我的代码:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.text.AttributeSet;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
public class SimpleEditor extends JFrame {
private static final long serialVersionUID = 1L;
private final JTextPane textPane;
private final HTMLEditorKit edtKit;
private final HTMLDocument doc;
private final StyleSheet predefStyles;
public static void main(String[] args) {
final SimpleEditor editor = new SimpleEditor();
editor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
editor.setVisible(true);
}
public SimpleEditor() {
super("Very Simple HTML Editor");
textPane = new JTextPane();
edtKit = new HTMLEditorKit();
textPane.setEditorKit(edtKit);
predefStyles = new StyleSheet();
predefStyles.addRule("MyStyle1 { color:#cc0000; background-color:silver }\n" +
"MyStyle2 { color:#0000cc; background-color:aqua }");
doc = new HTMLDocument(predefStyles);
textPane.setDocument(doc);
final Container content = getContentPane();
content.add(textPane, BorderLayout.CENTER);
content.add(createToolBar(), BorderLayout.NORTH);
setJMenuBar(createMenuBar());
setSize(500, 240);
}
private JToolBar createToolBar() {
final Vector<String> styleNames = new Vector<String>();
final Enumeration<?> names = predefStyles.getStyleNames();
while (names.hasMoreElements()) {
styleNames.add((String) names.nextElement());
}
final DefaultComboBoxModel<String> stylesModel =
new DefaultComboBoxModel<String>(styleNames);
final JComboBox<String> cbStyleSel = new JComboBox<String>(stylesModel);
final JToolBar bar = new JToolBar();
cbStyleSel.setEditable(false);
cbStyleSel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
e.getSource();
@SuppressWarnings("unchecked")
final JComboBox<CondStyle> cboStyleSel =
(JComboBox<CondStyle>) e.getSource();
final String selItem = (String) cboStyleSel.getSelectedItem();
final Style style = textPane.getStyle(selItem);
textPane.setCharacterAttributes(extractStyleAttribs(style), true);
SimpleEditor.this.requestFocus();
}
});
bar.add(cbStyleSel);
return bar;
}
/**
* Extracts the style attributes except the style's name
* @param aStyle The style to be processed
* @return The visual attributes extracted from the style
*/
AttributeSet extractStyleAttribs(Style aStyle) {
final MutableAttributeSet attribs = new SimpleAttributeSet();
final Enumeration<?> attribNames = aStyle.getAttributeNames();
while (attribNames.hasMoreElements()) {
final Object attribName = attribNames.nextElement();
if (attribName == Style.NameAttribute) {
continue;
}
attribs.addAttribute(attribName, aStyle.getAttribute(attribName));
}
return attribs;
}
private JMenuBar createMenuBar() {
final JMenuBar menubar = new JMenuBar();
final JMenu mnuFile = new JMenu("File");
menubar.add(mnuFile);
final ExitAction actSave = new ExitAction();
mnuFile.add(actSave);
return menubar;
}
class ExitAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public ExitAction() {
super("Save & Exit");
}
@Override
public void actionPerformed(ActionEvent ev) {
final JFileChooser chooser = new JFileChooser();
if (chooser.showSaveDialog(SimpleEditor.this) !=
JFileChooser.APPROVE_OPTION)
return;
final File file = chooser.getSelectedFile();
if (file == null)
return;
FileWriter writer = null;
try {
writer = new FileWriter(file);
textPane.write(writer);
} catch (final IOException ex) {
JOptionPane.showMessageDialog(SimpleEditor.this,
"File Not Saved", "ERROR",
JOptionPane.ERROR_MESSAGE);
} finally {
if (writer != null) {
try {
writer.close();
} catch (final IOException x) {
}
}
}
System.exit(0);
}
}
}
这是应用程序的屏幕截图,其中输入了一些样式文本:
保存文档 ( ) 时创建的 HTML 文件textPane.write(writer);
结构不正确。该<body> ... </body>
部分如下所示:
<body>
<p style="margin-top: 0">
default text
</p>
<p style="margin-top: 0">
<font color="#cc0000"><p style="background-color: silver">
</font> </p>
<p style="margin-top: 0">
<font color="#0000cc"><p style="background-color: aqua">
</font> </p>
<p style="margin-top: 0">
<font color="#333333" face="Dialog" size="3"><p FONT_ATTRIBUTE_KEY="javax.swing.plaf.FontUIResource[family=Dialog,name=Dialog,style=plain,size=12]">
</font> </p>
</body>
很明显,生成的 HTML 代码不正确。在<p>
元素内部创建了一个新<font>
元素,它定义了样式的前景色。然后<p>
创建另一个具有背景颜色定义的元素。但文字不见了。然后不是结束</p>
标签,而是结束</font>
标签,然后是</p>
结束外部<p>
元素的标签。我究竟做错了什么?