【问题标题】:How to print text on new line using "\n"如何使用“\n”在新行上打印文本
【发布时间】:2026-02-07 04:30:01
【问题描述】:

我尝试以我想要的适当格式创建一个大的String,并使用PrinterJob 类打印它。下面是String的代码:

String bigtext = "The name\n" + "some another text";
Graphics2D's_object.drawString(bigtext, 50, 50);

但它在一行中打印为"The name some another text""\n" 不起作用,而我想在另一行中打印"some another text"

附:我尝试在打印机中打印 bigtext。

已解决:这是解决方案:Problems with newline in Graphics2D.drawString。 (经过长时间的麻烦:))

【问题讨论】:

  • 您应该考虑在显示信息的位置添加代码,以便我们提供帮助
  • 你能提供一些代码sn-ps吗?我们知道如何连接字符串,但是如何打印它们呢?
  • 以格式化的方式提供您当前的输出和预期输出。我看不出两者有什么区别。
  • 帮我看看它的工作原理。这是你的代码ideone.com/YMNIXO
  • 仍然不明白“打印机”的意思。你有一个PrinterJob。您有 String 可以打印。那你怎么办?

标签: java


【解决方案1】:

换行符\n 不是在某些操作系统中使用\r\n 的行分隔符。另外我建议使用StringBuilder 而不是+

编辑:您也可以使用System.getProperty("line.separator");

【讨论】:

    【解决方案2】:

    昨天有人问了一个类似的question,这是有帮助的:

    您遇到的问题是因为您正在硬编码的“行分隔符”。最好使用以下方式获取系统的行分隔符:

    System.getProperty("line.separator");
    

    让你的代码看起来像这样:

       String lineseparator=System.getProperty("line.separator");
       // I'd suggest putting this as a class variable, so that it only gets called once
       // rather than everytime you call the addLine() method
    
      String bigtext = "The name" + lineseparator + "some another text";
    
     //If you wanted an empty line in between them, then add the lineseparator twice
      String bigtext = "The name" + lineseparator + lineseparator + "some another text";
    

    【讨论】:

    • 不幸的是,它没有帮助。
    • 你能把剩下的代码贴出来,以便我们帮助你吗?
    【解决方案3】:

    似乎大多数人不明白这个问题。我尝试了 PrinterJob,但它也不适合我。

    我找到了解决方案但未验证:

    How to print strings with line breaks in java

    【讨论】: