user123 user123 - 1 year ago 43
Java Question

Passing a String to JTextArea, not reading \n

If I call:

JTextArea textArea = new JTextArea("test\ntest", 15, 20);

The text area will display test on 2 lines as desired.

However, I would like to read text from a txt file using a scanner that finds a certain line, and then returns that as a string. In the txt file, I stored that particular line with \n included to save a step. But in the text area the string is just printed with the \n's in the text instead of returning to a new line.


//i.currentStats() returns a string
JTextArea textArea = new JTextArea(i.currentStats(), 15, 20);

//currentStats() uses readLastStats() to store String lastStats into String stats
public void readLastStats() {
while (sc.hasNext()) {
if ("Date")) {
lastDate =;
while (sc.hasNext()) {
if ("Stats")) {
lastStats = sc.nextLine();
stats = lastStats;
if(lastDate!=null) {

The images below show the txt file & what the textArea prints.

Answer Source

The transmutation of the character sequence \n to a newline is performed by the Java compiler. If you create a text file with the \n sequence, then read it, it will contain the 2 character sequence, not the newline character.

If you store it as 2 separate lines. Ex:


When you read it and display it it will appear as 2 lines. If you want to store it as a single line in the file, then you'll need to provide code to process the line and replace the \n sequence with an actual newline. For example:

myExpandedString = myStringFromFile.replaceAll("\\n", "\n");