First of all, the real answer is that this is how the designers thought the design should work. You'd really need to ask them to get the real reason(s).
Having said that:
So why doesn't JTextComponent.setText(String) normalize line endings?
I think that the most likely reasons are:
It would be unexpected behaviour. Most programmers would expect1 a 'get' on a text field to return the same string value that was 'set' ... or that the user entered.
If text fields did normalize, then the programmer would have great difficulty preserving the original text's line endings in vases where this was desirable.
The designers might have wanted to change their minds at some point (c.f. the reported behaviour of the
read
andwrite
methods) bur were unable to for reasons of compatibility.
Anyway, if you need normalization, there's nothing stopping your code from doing this on the value retrieved by the setter.
Or any other method that allows text to be modified within a text component for that matter?
It is reported (see comments) that read
and/or write
do normalization.
Is using System.getProperty('line.separator') a good practice when dealing with text components? Is it a good practice at all?
It depends on the context. If you know you are reading and writing files to be processed on "this" platform, its probably a good idea. If the file is intended to be read on a different platform (with a different line separators) then normalizing to match the current machine's convention is maybe a bad idea.
1 - The fact that other methods like read
and write
that may behave differently doesn't affect this. They are not "getters" and "setters". I'm talking about how people expect "getters" and "setters" to behave ... not anything else. Besides, people shouldn't expect everything to behave the same way, unless it is specified that they do. But obviously, the part of the problem here is that the spec ... the javadocs ... is silent on these issues.
The other possibility is that the normalization behaviour that @predi reports is actually happening in the Reader
/ Writer
objects ...