【问题标题】:New line within String text?字符串文本中的新行?
【发布时间】:2012-03-10 10:31:55
【问题描述】:

我正在尝试将大量文本添加到字符串中。为此,我需要在文本中添加一个新行,以便在打印时,所有内容都不会在一条直线上。如何在字符串文本中插入新行?

这是我的代码:

String writing = "7 Dear friends, let us love one another, for love comes from God. Everyone who loves has been born of God and knows God. 8 Whoever does not love does not know God, because God is love. 9 This is how God showed his love among us: He sent his one and only Son into the world that we might live through him. 10 This is love: not that we loved God, but that he loved us and sent his Son as an atoning sacrifice for our sins. 11 Dear friends, since God so loved us, we also ought to love one another. 12 No one has ever seen God; but if we love one another, God lives in us and his love is made complete in us. 1 Everyone who believes that Jesus is the Christ is born of God, and everyone who loves the father loves his child as well. 2 This is how we know that we love the children of God: by loving God and carrying out his commands. 3 In fact, this is love for God: to keep his commands. And his commands are not burdensome, 4 for everyone born of God overcomes the world. This is the victory that has overcome the world, even our faith. 5 Who is it that overcomes the world? Only the one who believes that Jesus is the Son of God.";

  JTextArea sampleWriting = new JTextArea();
  sampleWriting.setText(writing);
  sampleWriting.setFocusable(false);

  JTextField userTypingRegion = new JTextField();

  dataCollectionRegion.add(sampleWriting);
  dataCollectionRegion.add(userTypingRegion);

我试过 /n 但在 JTextArea 中,文字都在一行中。

【问题讨论】:

    标签: java string swing


    【解决方案1】:

    使用换行符:

    String x = "line 1\nline 2";
    

    【讨论】:

      【解决方案2】:

      试试这个:

      StringBuilder sb = new StringBuilder("long string");
      // adds a line separator
      sb.append(System.getProperty("line. separator"));
      sb.append("another long string");
      // ... more lines ...
      String result = sb.toString();
      

      上述代码的优点在于添加的行分隔符对于您所在的平台(Linux、Windows 等)是正确的

      编辑:

      既然您已经发布了代码,我可以看到它毕竟不是那么长的字符串 :) 。那么很简单,试试这个:

      String writing = "Hello. \nWorld. \nLamp.";
      

      【讨论】:

      • 对不起,我不知道如何将它应用到我最近刚刚发布的代码中。
      • 好吧,你的文字毕竟不是那么。使用这个,然后:String writing = "Hello. \nWorld. \nLamp.";
      猜你喜欢
      • 1970-01-01
      • 2015-09-14
      • 2023-01-02
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 2016-06-17
      • 2011-02-27
      相关资源
      最近更新 更多