0

我不知道这是否可能,但我想做的是在 .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);
        }
    });
}
}
4

1 回答 1

2

您可以使用RTFEditorKit,它支持富文本格式(RTF)。许多文字处理器,包括 MS Word,都可以使用这种格式。坚持使用write()OutputStream它写的是“适合这种内容处理程序的格式”。另一个使用 aWriter写入“以纯文本形式写入给定流”。

为什么StyledEditorKit不工作?

StyledEditorKit从“将文本视为纯文本”中获取其write()实现。在内部存储样式文本,但它不知道任何外部格式。您必须转到其中一个子类,或者,才能获得覆盖默认值的东西。被覆盖的方法知道如何将内部格式转换为外部格式,例如 RTF。DefaultEditorKitStyledEditorKitHTMLEditorKitRTFEditorKitwrite()

于 2017-06-21T10:05:28.887 回答