如何从JTextArea获取文本? [英] How to get text from JTextArea?

查看:1101
本文介绍了如何从JTextArea获取文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JFrame和JButton上有一个JTextArea.

I have a JTextArea on a JFrame and a JButton.

当用户在JTextArea textArea上键入字符并按下按钮时,我希望将信息保存在textFile中.

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();    } 

    }}

但是当我打开logsheet.txt时,什么也没看到.它的null.我是否需要像textArea.getText();这样的函数?我试过了,但出现错误.

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.

推荐答案

我猜测您的问题是您将文本区域定义为类变量和局部变量.您的ActionListener正在访问为null的类变量.

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.

//JTextArea textArea = new JTextArea(2, 20); // this is wrong, you don't want a local variable
textArea = new JTextArea(2, 20);

此外,使用textArea.write(...)方法是执行此操作的正确方法.您不想使用getText()方法,因为该方法可能会导致字符串中包含错误的换行符.

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.

这篇关于如何从JTextArea获取文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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