JTextPane clear text

Bv202 picture Bv202 · Dec 2, 2011 · Viewed 11.5k times · Source

I'm trying to remove all text from a JTextPane. I thought you could simply use:

textPane.setText(""); 

This DOES work, but for some reason, there always is an empty line after calling that method. Why is that and how do I prevent that?

Answer

camickr picture camickr · Dec 2, 2011

Probably because you are using a KeyListener to listen for the Enter key and then clear the text. Well JTextPane has an Action which adds a newline character when the Enter key is pressed and the is happening after you clear the text pane.

The proper solution is to use Key Bindings and replace the default Action with an action that clears the text pane.