Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(""); 
like image 501
Lord Rixuel Avatar asked Apr 03 '13 21:04

Lord Rixuel


People also ask

What happens if you press Enter in a JTextArea?

Press Enter to accept the completion or continue typing. The following code adds a document listener to the text area's document: textArea.

How do I disable JTextArea?

To disable JtextField/JTextArea, call the method setEnabled() and pass the value “false” as parameter. JTextField textField = new JTextField(); textField.

How do you clear a JButton in Java?

Java Program to Clear JTextArea by Clicking JButton: super("Clear the contents of a JTextArea"); JButton clearButton = new JButton("Clear"); clearButton.

How do you clear a textbox in Java?

Syntax: JButton jb_clear=new JButton("Clear"); Many times you have to clear the text field in java. This can be done by calling the clear() method of the JTextField class.


2 Answers

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 
like image 190
Kevin S Avatar answered Sep 21 '22 20:09

Kevin S


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.

like image 40
John Perczyk Avatar answered Sep 21 '22 20:09

John Perczyk