How to clear JTextArea?
Asked Answered
B

4

29

I'm trying to clear the JTextArea.

Currently, I'm using

jtextarea.setText(null);

What is the difference if I use

jtextarea.setText("");
Bet answered 3/4, 2013 at 21:32 Comment(2)
jtextarea.setText("") may be a drop slower the first time it is created (I mean, the empty string) since it is cached in an internal hashset. But this isn't even relevant on now days systems. The empty string may be - at some point - more readable.Hiramhirasuna
With questions like these, you can look up the source code for setText() and look at the difference yourself.Halliehallman
W
26

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
Waneta answered 3/4, 2013 at 21:38 Comment(1)
Please fix this link and reference proper Swing component JTextComponent and not AWT one. Also consider referencing rather latest javadoc, ie, 1.7Bari
W
3

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.

Westernmost answered 23/10, 2018 at 6:17 Comment(0)
C
1
JTextArea0.selectAll();
JTextArea0.replaceSelection("");
Combinative answered 29/5, 2017 at 6:32 Comment(1)
Please add some text to your answer in order to explain, what your code does and how it answers the initial question.Ardussi
K
0

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.

Karame answered 11/5, 2016 at 22:55 Comment(3)
What is 'an empty character'?Halliehallman
Empty character is kind a like space. In my Opinion. It is a character, but if you print it out. It will show nothing. But if you print out "null" it will show and actual text - null.Karame
'' is not an empty character, it is a zero-length string.Halliehallman

© 2022 - 2024 — McMap. All rights reserved.