向 java 格式化程序添加格式化
我正在编写一个记事本克隆来了解有关 guis 的更多信息。我的程序使用以下代码创建一个文本文件:
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");
}
如何保留文本的格式?我正在从 JTextArea 检索文件:
String contents = text.getText();
但基本上我丢失了所有格式。当我使用以下命令读取文件时,单词之间会出现空格:
字符串读取 = sc.next(); 打开文本=打开文本+“”+阅读;
无论如何,是否可以将格式存储在字符串中?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JTextArea 不支持任何“格式设置”。您所能做的就是在单词之间添加制表符或空格。如果文本没有按照您期望的方式排列,那么我猜您需要在文本区域中使用“等宽字体”。
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.
字符串有文本。文档可能有格式。 JTextArea可以显示一个Document。调用 getText() 将仅返回文本,而不返回格式。
Strings have text. Documents may have formatting. JTextArea can display a Document. Calling getText() will return only text, not formatting.