3

Any idea how I can add a text listener on to a JTextField, that triggers when the text changes and as an action modifies the JTextField's text.

I have tried using addInputMethodListener which seems to be appropriate but it doesn't seem to work. I have also tried textField.getDocument().addDocumentListener() but this throws java.lang.IllegalStateException: Attempt to mutate in notification when I try to modify textField's text.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Random42
  • 8,989
  • 6
  • 55
  • 86

1 Answers1

7

DocumentListeners do not permit the modification of the underlying document of the JTextComponent. You are looking for a DocumentFilter.

Example

Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • +1 [DocumentListeners](http://stackoverflow.com/a/8013129/714968), [DocumentFilter](http://stackoverflow.com/a/9430683/714968) – mKorbel Jan 13 '13 at 13:15
  • @Reimeus It doesn't work; it throws `StackOverFlowError` because when I change textField's text it calls `replace` from `DocumentFilter` which calls `setText` and thus in infinite recursion. – Random42 Jan 13 '13 at 13:16
  • @mKorbel I have said why it doesn't work with DocumentListener (and with DocumentFilter subsequently). – Random42 Jan 13 '13 at 13:18
  • 2
    Don't call `setText` in the `DocumentFilter`, use the `replace` method from the super class. – Reimeus Jan 13 '13 at 13:22
  • post an [SSCCE](http://sscce.org/), could eb based on my posts in my comment here, everything is hidden in your code, your problem, nobody knows about that:-) – mKorbel Jan 13 '13 at 13:22
  • @Reimeus immediatelly go to the lottery and to buy a few Lotto tickets, – mKorbel Jan 13 '13 at 13:25