for the following Code I get an IllegalStateException (Attempt to mutate in notification):
private class DocumentHandler implements DocumentListener {
public void changedUpdate(DocumentEvent ev) {
// unused
}
public void insertUpdate(DocumentEvent ev) {
if(textInput.getText().equals("...")) {
JOptionPane.showMessageDialog(null, "...");
textInput.setText("");
}
}
Why can´t I change a TextField while a DocumentListener is active?
I tried to remove the DocumentListener while the TextField is set to " " but that didn´t help at all. I know that someone asked a very similar question before, but I don´t get that answer...
Thanks
In general, you don't -- you don't change the state of the Document while listening to it when using a DocumentListener. The two possible solutions that I know of:
SwingUtilities.invokeLater(yourRunnable). This is a shameless kludgeUnrelated side issue: your code shows a worrisome degree of coupling in that you try to change the text in a specific text component from within your listener. DocumentListeners should be fully agnostic of the text component whose document that they listen to, and in fact may be added to more than one Document.
A DocumentFilter has 3 methods that need to be overridden and do what you expect them to do: what you would expect them to do:
insertString: insert a String into the documentremove: removes text from the documentreplace: replaces text in the documentWhat is more, these methods do their actions before the text component renders the changes to the document.
So within my method overrides, I extract the current document's text, and use the parameters to create what the new text will look like, for example for the replace method I did:
I then do a boolean test on the newText to see if it is "good", and if so, call the super's method, here
replace(...), passing in all the parameters. If not, if the newText fails the test, then I remove all the text from the document and show a JOptionPane.So in this example, I use this as my test method:
which tests to see if the text is any of the disallowed Strings, here
"...", " ", "oops", "OOPS", but it could be any Strings that you desire. Again, if the text passes the text, call the super's method, else remove the text:Where
badText(fb)does:The whole example is: