Lord Rixuel
Lord Rixuel

Reputation: 1233

How to clear JTextArea?

I'm trying to clear the JTextArea.

Currently, I'm using

jtextarea.setText(null);

What is the difference if I use

jtextarea.setText("");

Upvotes: 29

Views: 88584

Answers (4)

John Perczyk
John Perczyk

Reputation: 83

What the author was trying to was clear the JTextArea, not add a null character to it!

    JTextArea0.selectAll();
    JTextArea0.replaceSelection("");

This selects the entire textArea and then replaces it will a null string, effectively clearing the JTextArea.

Not sure what the misunderstanding was here, but I had the same question and this answer solved it for me.

Upvotes: 4

Mohammed Al-saleh
Mohammed Al-saleh

Reputation: 11

JTextArea0.selectAll();
JTextArea0.replaceSelection("");

Upvotes: 1

exploded Baloon
exploded Baloon

Reputation: 5

Actually There is the difference , i think so.

If you set it to null, The actual value written in text area will be nothing. But if you set it to "" it wil be an empty character. The same like you can set it to "z" and there will be written z, but null means unknow. You will not feal the difference until you gonna need to use the text written in textArea.

Upvotes: 0

Kevin S
Kevin S

Reputation: 2753

There is no difference. They both have the effect of deleting the old text. From the java TextComponent page:

setText

  public void setText(String t)

  Sets the text of this TextComponent to the specified text. If the text is null
  or empty, has the effect of simply deleting the old text. When text has been
  inserted, the resulting caret location is determined by the implementation of
  the caret class.

  Note that text is not a bound property, so no PropertyChangeEvent is fired when
  it changes. To listen for changes to the text, use DocumentListener.

  Parameters:
      t - the new text to be set
  See Also:
      getText(int, int), DefaultCaret

Upvotes: 26

Related Questions