Differences in getting text from a jTextPane

Hi,

I have recently been designing a text editor using swing and I have noticed that if I save file information like this:

//userText is a JTextPane object which the user can edit text in.

//The method saveText() just uses a standard BufferedWriter to

//save the text to a file.

saveText(userText.getText());

it messes up the line and column information of the file (as well as my findWord method).

However, if I save the file like this:

Document tempDoc = userText.getDocument();

try{

saveText(tempDoc.getText(0,tempDoc.getLength()));

}catch(BadLocationException e)

{

e.printStackTrace();

}

then all is alright with the world and little blue cartoon birds even perch on my shoulder as I sing happy songs.

Why? what is the one method doing that the other isn't?

thanks

Chris

[1159 byte] By [Flat_Doga] at [2007-10-3 3:46:28]
# 1

> Why? what is the one method doing that the other isn't?

In the Document the new line string is represented as "\n".

The getText() method of the JTextPane gets the text in a platform independent way. Which means that the new line string of the Document is replaced with the new line String of the platform.

In Windows the new line string is "\r\n". Therefore your find/replace logic will be off by one more for every additional line in the file.

So when you save the file you want to use textPane.getText(). For find/replace you want to use textPane.getDocument().getText(...).

Another option is to use the following:

textPane.getDocument().putProperty( DefaultEditorKit.EndOfLineStringProperty, "\n" );

Now the textPane.getText(...) method will work the same. However, when saving the file you would need to reset it to the platform specific EOL.

camickra at 2007-7-14 21:43:11 > top of Java-index,Desktop,Core GUI APIs...
# 2
Ah!The light of understanding dawns slowly in my baby-blue eyes. Thank you! That was very nicely explained, very clear and wossname..succinct... rare in this day and age ;)Cheers,Chris
Flat_Doga at 2007-7-14 21:43:11 > top of Java-index,Desktop,Core GUI APIs...