javaswingdocumentlistenerdocumentfilter

Autocomplete Text box with Document Listener in Java


I'm trying to make an autocomplete textbox for a program I'm writing. I have the logic down, but I'm having some trouble implementing it properly. First I tried it with a key listener, but that solution was a bit strange in the way that it handled multiple key presses at the same time. Then I tried DocumentListener which was far better, but doesn't allow me to edit the document from within the Listener because of a threading issue. I read something about DocumentFilter, but I can't find a single guide on how to use it. Is there a way of editing the doc from with documentListener? Or would you recommend DocumentFilter and if so, how do you use it??


Solution

  • DocumentListener should not be used to edit the document. Doing so would require a call to SwingUtilities.invokeLater(...) and since DocumentListener detects changes to the document, any edits would result in an infinite loop. Best bet is to use DocumentFilter.