向 java 格式化程序添加格式化

发布于 2024-11-15 06:45:26 字数 738 浏览 3 评论 0原文

我正在编写一个记事本克隆来了解有关 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鸢与 2024-11-22 06:45:26

JTextArea 不支持任何“格式设置”。您所能做的就是在单词之间添加制表符或空格。如果文本没有按照您期望的方式排列,那么我猜您需要在文本区域中使用“等宽字体”。

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

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) );
淤浪 2024-11-22 06:45:26

字符串有文本。文档可能有格式。 JTextArea可以显示一个Document。调用 getText() 将仅返回文本,而不返回格式。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文