简体   繁体   中英

How to append data in JTextArea in Java?

I am using this code to show text in a JTextArea :

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

But it shows an exception:

java.lang.NullPointerException

You never instantiated your JTextArea . Also, you might want to check out 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; for details, see the API documentation for DefaultEditorKit.

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. Otherwise, you will get a NullPointerException . Also note that appending a text to a JTextArea can be done easily by calling its JTextArea.append(String) method. 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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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