Reputation: 1253
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
Upvotes: 0
Views: 9842
Reputation: 900
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);
Upvotes: 0
Reputation: 3268
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);
}
}
Upvotes: 0
Reputation: 51
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.
Upvotes: 0
Reputation: 44808
You never instantiated your JTextArea
. Also, you might want to check out JTextArea#append
.
Upvotes: 4