Writing multiline JTextArea to txt file

2019-02-24 08:17发布

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

2条回答
倾城 Initia
2楼-- · 2019-02-24 09:00

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

查看更多
Bombasti
3楼-- · 2019-02-24 09:10

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?

查看更多
登录 后发表回答