Reputation: 227
I am using a JTextPane object, let's say its name is jtp, so I can show parts of a somewhat short String in italic or bold. I have a String, let's name it otxt that has a newline. Given I am using Windows it means \r\n and it is created using
System.getProperty("line.separator")
and to dissipate all doubts before they are fully formed, I converted my String to char array, walked the char array and written in the Eclipse console the codes of all characters using implicit conversion via casting to int and yes, there is only one code 13, representing \r and only one code 10, representing \n. Now, if I use
jtp.setText(otxt);
everything goes fine - I do the conversion to char array from
jtp.getText()
and printing out all characters' codes and I have only one code 13 (\r) and only one code 10 (\n) as I am supposed to have. But I need to show certain parts of otxt in italic or bold so I have to use
jtp.insertString(0 /*offset*/, otxt, attributeSet /*italic, bold or whatever stylistic property*/)
And here's the big problem: This creates \r\r\n where I am supposed to have \r\n. This is confirmed using the same procedure: 1) string from jtp.getText() to char array; 2) walking the array; 3) printing characters' codes; and I see code 13 (\r) twice and code 10 (\n) once. Help me battle this. Hope you find the question interesting.
Upvotes: 4
Views: 554
Reputation: 324118
The Document
class only stores a "\n"
in the Document. So you should not attempt to insert an "\r" character indo the Document.
If you want to add a newline to the Document
you just insert "\n"
.
When you use the getText()
of a text component the method will replace the "\n" characters in the Document with the newline string for your current platform.
So for Windows the "\n" will be replaced with "\r\n" for you.
Check out Text and New Lines for more information on this topic.
Upvotes: 5