Search code examples
javaswingevent-handlingmouselistenerjcomponent

Check if a JComponent hasMouseListener()


Is it possible to check if a JComponent already has a MouseListener attached to it?

For example, I am trying to create the hasMouseListener() method:

JComponent jComponent = getJComponent();
hasMouseListener(jComponent); //should be false
jComponent.addMouseListener(this);
hasMouseListener(jComponent); //should be true

An alternative solution would be a way to getMouseListener() so that I could check for null.


Solution

  • As kdgregory informed me, http://docs.oracle.com/javase/7/docs/api/index-files/index-7.html exists!

    jComponent.getMouseListeners() returns an array of all its MouseListeners. From there, I can just check its size.