Writing a multi-line JTextArea file to txt

so I have a JTextArea for user input, and then when they click the button, it writes it to a text file, I have both setLineWrap and setWrapStyleWord for true for JTextArea .

I would like to write to the text file the exact way that it appears in the text box.

I tried doing replace("\n", System.getProperty("line.separator")) on a String containing the contents of the JTextArea , which works, but only if the user actually clicks on the return key when entering the input, but if the user just continues to print and gets to the end of the line, so it jumps to the line below, replace does not work.

I also tried using StringBuffer , I calculated how many characters would fit in the string, and then ran the for loop inserting lines at the end of each line, so for the first line I would add it at position 90 , 2nd line at 180 , third line at 270 and so on. But soon I realized that it doesn’t work in all situations, because some characters are smaller than others, for example, you can put more j on one line than p .

What I would like to do is simply calculate the way to calculate the end of the line so that I know where insert new line, but I am open to other suggestions as well. Thank you If you think this helps to see some of my codes, just ask.

Update Instead of injecting the code to do this, I talked to a person who would be pretty much one of those who use this program, and he was fine with the usual notepad format, and I didn’t understand this, but until then as long as he has wordWrap checked in his notepad formatting, this will save him from having to use side scrolling to read the entire line, thanks for your input

+4
source share
2 answers

Use Utilities Class

 public static final int getRowStart(JTextComponent c, int offs) public static final int getRowEnd(JTextComponent c, int offs) 

you pass the offset and get the offset of the beginning and end of the line

+5
source

I don’t see how, except to simply calculate the lengths of words using font metrics, and do what the text area already does.

What is the purpose of this though?

+1
source

All Articles