2017-06-21 54 views
0

我不知道這是否可能,但我想要做的是在.doc文件中保存一個樣式文檔(用戶可以更改文本:粗體,下劃線,斜體和3種字體大小) - 如此他以後可以用任何支持樣式文本的其他文本編輯器自行打開它。如何將textPane中的StyledDocument保存到.doc文件中?

我寫了下面的代碼...編輯器工作,我可以在文本上應用樣式,但是當我保存時,它將文本保存爲黑色,沒有樣式。我無法弄清楚問題在哪裏。也許行動不保存。我試着用作家和緩衝作家,但它沒有奏效。我也嘗試使用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); 
     } 
    }); 
} 
} 

回答

2

您可以使用RTFEditorKit,它支持Rich Text Format(RTF)。包括MS Word在內的許多文字處理軟件都可以使用這種格式。堅持write()OutputStream,它寫道「適合這種內容處理程序的格式」。另一個使用Writer將「以純文本的形式寫入給定的流」。

爲什麼StyledEditorKit無法正常工作?

StyledEditorKit得到它從DefaultEditorKitwrite()實施, 「它把文本爲純文本。」 StyledEditorKit在內部存儲風格文本,但它不知道任何外部格式。您必須轉到其中一個子類HTMLEditorKitRTFEditorKit,才能獲得覆蓋默認值write()的內容。重寫的方法知道如何將內部格式轉換爲外部格式,如RTF。

+0

是否真的沒有其他方式,但使用不同的(在這種情況下,RTF格式)?爲什麼StyledEditorKit不起作用?我敢打賭,我只是沒有以正確的方式挽救一些東西...... – Ves

+0

我認爲這就是它設計的方式。我試着在上面解釋。 –

+0

卡塔利娜島謝謝你的解釋..我會先嚐試使用HTML,並讓你知道我是否有任何問題。 – Ves

相關問題