I don't know if this is even possible, but what I would like to do is to save a Styled Document (user can change text: bold, underline, italic and 3 sizes of font) in a .doc file - so he could open it later on his own with any other text editor that supports styled text.
I wrote the code below... the editor works, I can apply the styles on the text but when I save, it saves the text just black, with no styles. I can't figure out where is the problem. Maybe the actions don't save. I tried with writer and with buffered writer but it didn't work. I also tried to use HTML editor kit and it didn't work at all - it saved a blank document.
Maybe anyone has an idea how can I save the styles? Appreciate the help :)
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);
}
});
}
}