The JTextArea does not have an easy method for this type of text retrieval. Honestly, if this is a functionality you absolutely require, I have some steps to follow for a possible solution.
First, set the font of that JTextArea to a monospace font. For instructions on how to do this, see here.
After you have done that, set the JTextArea to have a fixed width, and figure out how many characters would fit in a line with that fixed width.
Once you know how many characters fit in a line, create a final int of that number in your class. Read in the String using the regular getText()
method, and break it up into sections based on that number. For a possible solution on how to do that, see here.
From there, append the \n
to each line as you please.
I understand this would be a messy solution and that it removes the ability to dynamically change the width of your JTextArea, but I believe it would work if implemented properly. Let me know if you have any questions.
Hope this helps!
UPDATE: This might actually not work if WrapStyleWord
is set to true
. You might still be able to figure it out though using the main idea of this method. The number of characters per line wouldn't change, but if you're in the middle of a word, you'd have to jump back to the beginning of it before you break.