如何从 JTextArea 获取文本?
我在 JFrame 和 JButton 上有一个 JTextArea。
当用户在 JTextArea 文本区域上键入字符并按下按钮时,我希望将信息保存在文本文件中。
JTextArea textArea = new JTextArea(2, 20);
textArea.setLineWrap (true);
thehandler4 handler4 = new thehandler4(); // next button
button4.addActionListener(handler4);
private class thehandler4 implements ActionListener{ //next button
public void actionPerformed(ActionEvent event){
PrintWriter log = null;
try {
FileWriter logg =new FileWriter("logsheet.txt",true);
log = new PrintWriter(logg);
log.println("Quick Notes: "+textArea);
log.close();
} catch( Exception y ) { y.printStackTrace(); }
}}
但是当我打开 logsheet.txt 时,我看不到任何东西。它为空。是否有我需要的函数,例如 textArea.getText();我尝试过,但出现错误。
I have a JTextArea on a JFrame and a JButton.
When user types characters on the JTextArea textArea and presses the button, I want the information to be saved in a textFile.
JTextArea textArea = new JTextArea(2, 20);
textArea.setLineWrap (true);
thehandler4 handler4 = new thehandler4(); // next button
button4.addActionListener(handler4);
private class thehandler4 implements ActionListener{ //next button
public void actionPerformed(ActionEvent event){
PrintWriter log = null;
try {
FileWriter logg =new FileWriter("logsheet.txt",true);
log = new PrintWriter(logg);
log.println("Quick Notes: "+textArea);
log.close();
} catch( Exception y ) { y.printStackTrace(); }
}}
But when I open the logsheet.txt, I don't see any thing. its null. is there a function I need like textArea.getText(); i tried that but I get an error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我猜你的问题是你将文本区域定义为类变量和局部变量。您的 ActionListener 正在访问为 null 的类变量。
此外,使用 textArea.write(...) 方法是执行此操作的正确方法。您不想使用 getText() 方法,因为该方法可能会导致字符串中包含错误的换行符。
I'm guessing your problem is that you have your text area defined as a class varaible and a local variable. Your ActionListener is accessing the class variable which is null.
Also, using the textArea.write(...) method is the proper way to do this. You don't want to use the getText() method, because that approach may result in the wrong newline characters being contained in the string.
您可以执行以下操作:
write() 方法允许您将文本从文本区域写入写入器。
You could do the following instead:
The write() method allows you to write text from text area to a writer.