0

I am trying to make a Text Editor in Java , but I have a few problems.

I can add an image to the with JTextPane with insertIcon(), but when I save it the file is empty ,I am trying to save it as a .doc . Its the same when I try to change the font , it works in JTextPane but when I save its a default font , not the font/size I had.

This is my saveFile method:

      try {
        BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
        writer.write(text.getText());
        writer.close();
        saved = true;
    } catch (IOException err) {
        err.printStackTrace();
    }
}

Thanks in advance :P

EDIT:

I am inserting an image in my JTextPane like this :

JFileChooser open = new JFileChooser();
            open.showOpenDialog(null);
            File file = open.getSelectedFile();
            Icon image = new ImageIcon(String.valueOf(file));
           text.insertIcon(image);

I am saving the JTextPane to a file using the saveFile method from above. The image is being added to the JTextPane , everything is fine .But when I open the file the image isnt there.

Nicu D
  • 27
  • 1
  • 8

2 Answers2

0

You could try flushing the writer before you close it. Add the line writer.flush(). This will flush the underlying outputstream. Essentially here the writing to the file begins.

Edit: I tested the code and it writes to a file. Is your problem that the font is not the same as it was before you saved it?

  • Yes , and when I insert an image , it wont save to the file. – Nicu D Oct 29 '16 at 13:55
  • The image does not save to the file? You are only writing the text. To save the whole component you would have to do what Andrew suggested. This saves the current state of the component. And not just the text. – Laurens Op 't Zandt Oct 29 '16 at 14:11
  • I tried what he said it doesnt work , maybe I didnt do it right ? text.write(writer); – Nicu D Oct 29 '16 at 14:17
0

You need to use the EditorKit. I'll write a more precise answer tomorrow.

Sharcoux
  • 5,546
  • 7
  • 45
  • 78