【问题标题】:Append Text to JTextArea on Multiple Lines?在多行上将文本附加到 JTextArea?
【发布时间】:2015-04-03 04:25:57
【问题描述】:

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

2
4
5
10
20
25
50

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

24510202550

如何使 JTextArea 看起来像带有单独行的数字的输出?谢谢!

【问题讨论】:

  • 到目前为止你做了什么?
  • "我有一个包含多个数字的字符串" - 一个实际的字符串?还是您的意思是列表?
  • 我建议使用System.getProperty("line.separator"); 而不是硬编码\n 作为换行符。
  • 是的,它是一个整数,我将其转换为字符串以显示在文本区域上,我现在可以使用它了。

标签: java string swing jtextarea


【解决方案1】:

将换行符 \n 放在字符串的末尾

【讨论】:

    【解决方案2】:

    您的 JTextArea 扩展了 JTextComponent,因此有自己的 read(...) 方法,允许它读取文本文件(以及其他内容),以依赖于操作系统的方式理解它们,然后显示它们,并用换行符完成。例如,请参阅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) {}
            }
         }
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 哈哈,谢谢,我知道我需要\n,只是不知道如何添加。
      猜你喜欢
      • 2014-03-06
      • 1970-01-01
      • 2011-06-18
      • 2015-09-04
      • 2023-03-30
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多