简体   繁体   English

如何清除 JTextArea?

[英]How to clear JTextArea?

I'm trying to clear the JTextArea.我正在尝试清除 JTextArea。

Currently, I'm using目前,我正在使用

jtextarea.setText(null);

What is the difference if I use如果我使用有什么区别

jtextarea.setText("");

There is no difference.没有区别。 They both have the effect of deleting the old text.它们都有删除旧文本的效果。 From the java TextComponent page:从 java TextComponent页面:

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

What the author was trying to was clear the JTextArea, not add a null character to it!作者试图清除 JTextArea,而不是向其中添加空字符!

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

This selects the entire textArea and then replaces it will a null string, effectively clearing the JTextArea.这将选择整个 textArea,然后将其替换为空字符串,从而有效地清除 JTextArea。

Not sure what the misunderstanding was here, but I had the same question and this answer solved it for me.不知道这里有什么误解,但我有同样的问题,这个答案为我解决了。

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

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.同样的,你可以把它设置为“z”,就会写成z,但null表示不知道。 You will not feal the difference until you gonna need to use the text written in textArea.除非您需要使用在 textArea 中编写的文本,否则您不会感受到差异。

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

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