> > area.append("\n");
> > // OR
> > area.append("\r\n");
>
> Does the choice matter? Discuss.
Use "\r\n" on windows, "\n" on unixes. Better yet, use System.getProperty("line.separator").
As for the differences between append(String) and setText(String), append() appends the string to the end, whereas setText() depends on the current caret position, as far as I can remember.
Jukka
"\n" or "\r\n"? Either way looks the same when you look at a text area, but when you write text to a file (textArea.write(writer)), there will be a difference
import java.io.*;
import javax.swing.*;
public class NewLine {
public static void main(String[] args) throws IOException {
System.out.println("\\r is " + (int)'\r');
System.out.println("\\n is " + (int)'\n');
test("\n");
test("\r\n");
}
static void test(String text) throws IOException {
JTextArea area = new JTextArea();
area.setText(text);
File file = new File("junk.txt");
Writer w = new FileWriter(file);
area.write(w);
w.close();
System.out.println("file content:");
InputStream in = new FileInputStream(file);
int ch;
while ((ch = in.read()) != -1) {
System.out.println(ch);
}
in.close();
}
}
I ran this on Windows and got this ouput:
\r is 13
\n is 10
file content:
13
10
file content:
13
13
10
Conclusion: use "\n". If you use "\r\n" under Windows, it will be written out as "\r\r\n". So don't worry about the platform, the write method handles that for you.
> As for the differences between append(String) and
> setText(String), append() appends the string to the
> end, whereas setText() depends on the current caret
> position, as far as I can remember.
From what the Op intends to achieve it's apt for him/her to use append and not setText . The reason for this is that setText clears the prevous data in the JTextArea and the resets it with the new text , unlike append which adds the new string to the end of the jtextarea . But there is a catch here . Append always adds to the end of the jtextarea . If the Op wants to add a new line inbetween then he would have to use insert(String,pos) to insert a new line .