Writing multiline JTextArea to txt file

与世无争的帅哥 提交于 2019-12-04 04:10: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


回答1:


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




回答2:


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?



来源:https://stackoverflow.com/questions/7648064/writing-multiline-jtextarea-to-txt-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!