How to clear a string?

kullalok picture kullalok · Jun 19, 2012 · Viewed 66.3k times · Source

In a program I'm working on, a textfield has to display some text at some point.

output.setText( outputString );
outputString = "";

output is a JTextField. These lines of code are in a method, and when it is called the first time, it works perfectly fine. However, when it is called another time, the original outputString text still remains. Why does this happen, and how can I fix it?

Okay, I think it happens because strings are immutable. The thing is, outputString never changes, so it still has the text from the initial method call.

How do I, somehow, change the text in the string?

Answer

Theodore Murdock picture Theodore Murdock · Jun 19, 2012

Setting the text to the contents of your variable does not set up a permanent relationship between that variable and that text field, if you want to clear the text, you could use

output.setText("");