将多行JTextArea写入txt文件 [英] Writing multiline JTextArea to txt file

查看:112
本文介绍了将多行JTextArea写入txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个JTextArea供用户输入,然后当他们单击按钮时将其写入文本文件,我将JTextAreasetLineWrapsetWrapStyleWord都设置为true. /p>

我想将其在文本框中显示的确切方式写入文本文件.

我试图在String上做一个replace("\n", System.getProperty("line.separator"))来保存JTextArea的内容,但前提是用户在键入输入时实际上按下了回车键,但前提是用户只是继续键入并敲到一行的末尾,因此它跳到了它下面的行,replace不起作用.

我也尝试过使用StringBuffer,我计算了可以容纳多少个字符,然后在每行末尾运行for loop inserting新行,因此对于第一行,我将其添加在位置90,第二行在180,第三行在270,依此类推.但是我很快意识到,这并不是在所有情况下都可行,因为某些字符比其他字符要小,例如,与p相比,单行中可以容纳更多的j.

我想做的只是找出一种计算行尾的方法,这样我就知道在哪里insert新行,但是我也愿意接受其他建议.谢谢.如果您认为查看我的一些代码会有所帮助,请询问.

更新 我没有执行代码来实现此目的,而是与将要使用该程序的唯一的人进行了交谈,他对常规记事本格式很好,但我没有意识到这一点,但是只要他在记事本中检查了wordWrap格式设置,那么他将无需使用侧向滚动键即可读取整行,谢谢您的输入

解决方案

使用 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

这篇关于将多行JTextArea写入txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆