adding formatting to java formatter
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 any开发者_高级运维way 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.
精彩评论