在多行上将文本附加到 JTextArea?

Append Text to JTextArea on Multiple Lines?

我有一个包含多个数字的字符串,打印出来时看起来像这样:

2
4
5
10
20
25
50

但是,当我将字符串附加到 JTextArea 时,它看起来像这样:

24510202550

如何使 JTextArea 看起来像数字在不同行上的输出?谢谢!

在字符串末尾添加换行符\n

您可能正在使用 System.out.println() 打印到控制台。 System.out.println() 将为您在每一行的末尾添加 '\n' 个字符。

但要以相同的方式将字符串输出到 JTextArea,请使用 jTextArea.append('\n');

您的 JTextArea 扩展了 JTextComponent,因此拥有自己的 read(...) 方法,允许它读取文本文件(以及其他内容),以 OS 相关的方式理解它们,然后显示他们,完成换行。例如,请参阅 this code 本质上,

     BufferedReader br = null;
     try {
        br = new BufferedReader(new FileReader(file));
        textArea.read(br, null); // here we read in the text file
     } catch (FileNotFoundException e) {
        e.printStackTrace();
     } catch (IOException e) {
        e.printStackTrace();
     } finally {
        if (br != null) {
           try {
              br.close();
           } catch (IOException e) {}
        }
     }