You can't modify the textfield's doucment inside a DocumentListener. Use a DocumentFilter
to modify text.
Document listeners should not modify the contents of the document; The
change is already complete by the time the listener is notified of the
change. Instead, write a custom document that overrides the
insertString or remove methods, or both.
In another part.
You may want to change the document's text within a document listener.
However, you should never modify the contents of a text component from
within a document listener. If you do, the program will likely
deadlock. Instead, you can use a formatted text field or provide a
document filter.