Search code examples
javaswingawtjcomponent

Get all listeners from javax.swing.text.Document instances


I have a JTextField instance with DocumentListener registered. I'd like to remove the documentListener using this method :

jTextField.getDocument().removeDocumentListener(arg0)

The issue I am running into, is that I can't access the document listener, as the Document class doesn't offer a getListeners() Method.

How can I get all listeners registered into a javax.swing.text.Document object.


Solution

  • If you know what Document is inside you can cast the result to something that has a getListeners() method.

    e.g.

    Document doc = jTextField.getDocument();
    if (doc instanceof AbstractDocument) {
        DocumentListener[] listeners = ((AbstractDocument) doc).getDocumentListeners();
        // find listener in array and remove
    }