我不知道这是否可能,但我想做的是在 .doc 文件中保存一个样式化文档(用户可以更改文本:粗体、下划线、斜体和 3 种字体大小) - 所以他可以稍后使用任何其他支持样式文本的文本编辑器自行打开它。
我写了下面的代码......编辑器工作,我可以在文本上应用样式但是当我保存时,它将文本保存为黑色,没有样式。我无法弄清楚问题出在哪里。也许行动不保存。我尝试使用作家和缓冲作家,但它没有用。我还尝试使用 HTML 编辑器工具包,但它根本不起作用 - 它保存了一个空白文档。
也许有人知道如何保存样式?感谢帮助:)
public class EditFrame extends javax.swing.JFrame {
JFrame frameEdit = this;
File file; //A file I would like to save to -> fileName.doc
StyledDocument doc;
HashMap<Object, Action> actions;
StyledEditorKit kit;
public EditFrame() {
super();
initComponents();
JMenu editMenu = createEditMenu();
}
protected JMenu createEditMenu() {
JMenu menu = editMenu;
Action action = new StyledEditorKit.BoldAction();
action.putValue(Action.NAME, "Bold");
menu.add(action);
action = new StyledEditorKit.ItalicAction();
action.putValue(Action.NAME, "Italic");
menu.add(action);
//...
return menu;
}
//I'm guessing this doesn't work correctly too (doesn't read styles), but this is another subject :)
public void readFile(File f) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "windows-1250"));
textPane.read(reader, null);
textPane.requestFocus();
} catch (IOException ex) {
Logger.getLogger(EditFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
//SAVE METHOD
private void save(java.awt.event.ActionEvent evt) {
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
kit = (StyledEditorKit) textPane.getEditorKit();
doc = (StyledDocument) textPane.getDocument();
kit.write(out, doc, 0, doc.getLength());
} catch (FileNotFoundException ex) {
Logger.getLogger(EditFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException | BadLocationException ex) {
Logger.getLogger(EditFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(EditFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new EditFrame().setVisible(true);
}
});
}
}