简体   繁体   中英

Writing multiline JTextArea to txt file

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

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

I have tried to do a replace("\\n", System.getProperty("line.separator")) on the String holding the contents of the JTextArea which works, but only if the user actually hits the return key when typing the input, but if the user just keeps typing and hits the end of a line so it jumps to the line below it, the replace doesnt work.

I have also tried using a StringBuffer , I calculated how many characters would fit in on line and then ran a for loop inserting new lines at the end of each line so for the first line I would add it at position 90 , 2nd line at 180 , third at 270 and so on. But I soon realized that does not work in all situations because some characters are smaller than others for example you could fit more j 's on a single line than p 's.

What I would like to do is just figure out a way calculate the end of a line so I know where to insert the new line, but I am open to other suggestions as well. Thanks. If you think it would help to see some of my code just ask.

Update Instead of implementing code to do this, I talked to the person who will be pretty much one of the only people using this program and he was fine with regular notepad format and I didnt realize it but as long as he has wordWrap checked in his notepad format settings then that will eliminate him having to use the side scroll in order to read the entire line, Thanks for your input

Use Utilities class

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

you pass offset and get offset of the row start and end

I don't see how, except to just calculate word lengths using font metrics and do what the text area already does.

What's the purpose behind this, though?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM