简体   繁体   English

将多行JTextArea写入txt文件

[英]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 . 所以我有一个用于用户输入的JTextArea ,然后当他们点击一个按钮将它写入文本文件时,我将setLineWrapsetWrapStyleWord设置为JTextArea true

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. 我试图在String上执行replace("\\n", System.getProperty("line.separator")) ,其中包含JTextArea的内容,但是只有当用户在键入输入时实际点击返回键时,但如果用户只是一直打字并点击一行的末尾,使其跳转到它下面的一行,则replace不起作用。

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. 我也试过使用一个StringBuffer ,我计算了在线上适合多少个字符,然后在每一行的末尾运行一个for loop inserting新行,所以对于第一行,我将它添加到位置90 ,第二行添加到180 ,第三名是270 ,依此类推。 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. 但我很快意识到,并非在所有情况下工作,因为有些字是比别人更小,例如,你可以容纳更多j '上比单一线S p的。

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. 我想做的只是找出计算一行结束的方法,以便知道在哪里insert新行,但我也对其他建议持开放态度。 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 更新而不是实现代码来执行此操作,我与那些将成为使用此程序的唯一人之一的人进行了交谈,并且他对常规记事本格式很好并且我没有意识到这一点,但只要他已经检查了wordWrap然后,记事本格式设置将消除他必须使用侧滚动以读取整行,感谢您的输入

Use Utilities class 使用Utilities

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? 但这背后的目的是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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