Question

I extended AWTEventListener, and then added it to the toolkit. However, when I try to assert that my listener is in the AWTListeners, my assertion fails. I call this from within the listener (although I don't know why that would cause a problem).

Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.MOUSE_EVENT_MASK
                                              | AWTEvent.KEY_EVENT_MASK
                                              | AWTEvent.MOUSE_MOTION_EVENT_MASK
                                              | AWTEvent.MOUSE_WHEEL_EVENT_MASK);
assert ArrayUtils.contains
                      (Toolkit.getDefaultToolkit().getAWTEventListeners(), this);
Was it helpful?

Solution

The AWTEventListeners within the default toolkit are maintained as proxies (java.awt.event.AWTEventListenerProxy), which wrap the listeners that were added.

Toolkit.getDefaultToolkit().addAWTEventListener(this, ...);

for (AWTEventListener listener : Toolkit.getDefaultToolkit().getAWTEventListeners()) {

    java.awt.event.AWTEventListenerProxy proxy = (java.awt.event.AWTEventListenerProxy) listener;
    if (proxy.getListener().equals(this) {
        // there, we found it.
    }
}

OTHER TIPS

As per source code of Toolkit it internally uses proxy as shown below that's assert is failed.

To prove this simply print the hash code of of the listener object that you passed and that is returned from getAWTEventListeners().

Alternatively you can check on Listener class name.

public void addAWTEventListener(AWTEventListener listener, long eventMask) {
    AWTEventListener localL = deProxyAWTEventListener(listener);

    if (localL == null) {
        return;
    }
    ...
}

static private AWTEventListener deProxyAWTEventListener(AWTEventListener l)
{
    AWTEventListener localL = l;

    if (localL == null) {
        return null;
    }
    // if user passed in a AWTEventListenerProxy object, extract
    // the listener
    if (l instanceof AWTEventListenerProxy) {
        localL = (AWTEventListener)((AWTEventListenerProxy)l).getListener();
    }
    return localL;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top