1

I have a JTextArea control in my Java application named txtInput. I have set lineWrap to true and wrapWordStyle to true as well.

When I click a button control is it possible for the line breaks to be incorporated into the String (from the JTextArea control) automatically or do I have to process the string?

So for example if my entered text is:

JTextArea example

Then my string would be something like

"this is a test to see if I \n can get the new lines \n incorporated"

Thanks.

Silentbob
  • 2,805
  • 7
  • 38
  • 70

2 Answers2

0

It's not possible to get the \n directly but you could process the String and introduce the \n manually: First of all you've to get all the different lines in the text separated in an array. String[] lines = yourTextArea.getText().split("\\n"); Then join them together in a variable String finalText with the \n included: for(int I=0; I<lines.lenght;I++){finalText = finalText+lines[I]+" \n "} and the finalText will be the text you've introduced with the \n at the end of each line.

Alex CuadrĂ³n
  • 638
  • 12
  • 19
0

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.

Francis Bartkowiak
  • 1,374
  • 2
  • 11
  • 28