java 如何从 JTextArea 获取文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5319397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:36:53  来源:igfitidea点击:

How to get text from JTextArea?

javaswingjtextarea

提问by razshan

I have a JTextArea on a JFrame and a JButton.

我在 JFrame 和 JButton 上有一个 JTextArea。

When user types characters on the JTextArea textArea and presses the button, I want the information to be saved in a textFile.

当用户在 JTextArea textArea 上键入字符并按下按钮时,我希望将信息保存在 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.

但是当我打开 logsheet.txt 时,我什么也没看到。它的空值。有没有我需要的函数,比如 textArea.getText(); 我试过了,但出现错误。

回答by camickr

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.

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

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

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.

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

回答by Amokrane Chentir

You could do the following instead:

您可以改为执行以下操作:

JTextArea textArea = new JTextArea(2, 20);
FileWriter logg =new FileWriter("logsheet.txt",true);
textArea.write(logg);

The write() method allows you to write text from text area to a writer.

write() 方法允许您将文本区域中的文本写入编写器。