简体   繁体   English

Java中的JTextArea中的append数据如何获取?

[英]How to append data in JTextArea in Java?

I am using this code to show text in a JTextArea :我正在使用此代码在JTextArea中显示文本:

jTextArea1.setText(jTextArea1.getText() + text + "\r\n");
jTextArea1.repaint();

But it shows an exception:但它显示了一个例外:

java.lang.NullPointerException

You never instantiated your JTextArea .您从未实例化您的JTextArea Also, you might want to check out JTextArea#append .另外,您可能想查看JTextArea#append

jTextArea1.setText(jTextArea1.getText() + text + "\r\n");

StringBuilder sb = new StringBuilder();
if(jTextArea1.getText().trim().length() > 0){
    sb.append(jTextArea1.getText().trim());
}
sb.append(text).append("\r\n");

jTextArea1.setText(sb.toString());

Above two friends gave you answer.以上两位朋友给了你答案。 I want to explain it.我想解释一下。 Because first times I also met that problem.因为我也是第一次遇到这个问题。 I solved that, but today solve as above code snippet.我解决了这个问题,但今天按照上面的代码片段解决了。

The following code adds text to the text area.以下代码将文本添加到文本区域。 Note that the text system uses the '\n' character internally to represent newlines;请注意,文本系统在内部使用 '\n' 字符来表示换行符; for details, see the API documentation for DefaultEditorKit.有关详细信息,请参阅 DefaultEditorKit 的 API 文档。

private final static String newline = "\n";
...
textArea.append(text + newline);

Source 资源

As Jeffrey pointed out, you have to create an object instance before you call non-static methods on it.正如 Jeffrey 指出的那样,您必须先创建一个 object 实例,然后才能对其调用非静态方法。 Otherwise, you will get a NullPointerException .否则,您将得到一个NullPointerException Also note that appending a text to a JTextArea can be done easily by calling its JTextArea.append(String) method.另请注意,可以通过调用JTextArea.append(String)方法轻松将文本附加到JTextArea See the following example code for more detail.有关详细信息,请参阅以下示例代码。


package test;

import javax.swing.JFrame;
import javax.swing.JTextArea;

public class Main {
  public static void main(String[] args) {
    Main m = new Main();
    m.start();
  }
  private void start() {
    JTextArea ta = new JTextArea();
    ta.append("1\n");
    ta.append("2\n");
    ta.append("3\n");
    JFrame f = new JFrame();
    f.setSize(320, 200);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(ta);
    f.setVisible(true);
  }
}

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

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