I'm writing a notepad clone to learn more about guis. My program creates a text file with the code:

                try {
                    formatter = new Formatter(fileName+".txt");                 
                    formatter.format(contents);
                    formatter.close();
                    JOptionPane.showMessageDialog(null, "File saved as "+fileName +".txt");

                } catch (Exception e){
                    JOptionPane.showMessageDialog(null, "Error writing to file");
                }

How can I keeping the formatting on my text? I'm retrieving the file from a JTextArea with:

String contents = text.getText();

but basically I lose all formatting. I get spaces back in between words when I read from the file with:
String reading = sc.next(); openedText = openedText + " " + reading;

Is there anyway to store formatting in a string?

有帮助吗?

解决方案

A JTextArea doesn't support any "formatting". All you can do is add tabs or spaces between words. If the text doesn't line up the way you expect then I would guess you need to use a "monospaced font" in your text area.

textArea.setFont( new Font("monospaced", Font.PLAIN, 10) );

其他提示

Strings have text. Documents may have formatting. JTextArea can display a Document. Calling getText() will return only text, not formatting.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top