user123 user123 - 4 months ago 13
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.

Why?

//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 (sc.next().equals("Date")) {
lastDate = sc.next();
//n++;
while (sc.hasNext()) {
if (sc.next().equals("Stats")) {
lastStats = sc.nextLine();
stats = lastStats;
}
}
}
}
if(lastDate!=null) {
timeDrain();
}
}


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


http://i.stack.imgur.com/WicIO.png

http://i.stack.imgur.com/O3J9F.png

Answer

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:

test
test

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");
Comments