2012-02-20 47 views
1

我正在將大量文本添加到字符串中。爲此,我需要在文本中添加一個新行,以便在打印時,所有內容都不會處於一條直線上。如何在字符串文本中添加新行?字符串文本中的新行?

這是我的代碼:

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中,寫作是在一個單一的線。

回答

6

使用換行字符:

String x = "line 1\nline 2"; 
6

試試這個:

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."; 
+0

對於'StringBuilder'和'line.separator' +1。 – RanRag 2012-02-20 01:33:45

+0

對不起,我沒有看到如何將這個應用到我最近剛剛提出的代碼中。 – Maydayfluffy 2012-02-20 01:41:17

+0

好,你的文字畢竟不是_that_。使用這個,然後:'String writing =「Hello。\ nWorld。\ nLamp。」;' – 2012-02-20 01:44:42