我不知道这是否可能,但我想要做的是在.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);
}
});
}
}
发布于 2017-06-21 02:05:28
您可以使用RTFEditorKit
,它支持富文本格式 (RTF)。许多字处理器,包括MS Word,都可以使用这种格式。坚持使用write()
到OutputStream
,它编写“适合这种内容处理程序的格式”。另一个使用Writer
的程序将“以纯文本形式写入给定的流”。
为什么
StyledEditorKit
不能工作?
StyledEditorKit
从DefaultEditorKit
获得它的write()
实现,“它将文本作为纯文本来处理。”StyledEditorKit
在内部存储样式文本,但它不知道任何外部格式。您必须转到其中一个子类HTMLEditorKit
或RTFEditorKit
,才能获得覆盖默认的write()
。重写的方法知道如何将内部格式转换为外部格式,如RTF。
https://stackoverflow.com/questions/44670616
复制