I have a JFrame with a lot of subcomponents and subpanels with different functions. I have added mouseListeners to some of them.
I want to be able to call a function when a mousebutton is clicked in the frame, regardless of what component is at focus. I dont want to add mouselisteners to all of the components. Much like keyEventDispacher, I am useing it for the keyboard.
I have looked at this Dispatch MouseEvent but I wasn’t able to work it out. Could anyone give me a small example to demonstrate how it works?
Here is a simple example of global mouse listener:
Be aware that this listener will inform you about every mouse event inside any frame/dialog/window/popup. That is why you should limit your actions to some specific frame like i did in the example in case you don’t need events from other frames/windows/…
By the way, you can easily listen to some other events globally (for example key events) using the same approach. For example – use the AWTEvent.KEY_EVENT_MASK key instead of AWTEvent.MOUSE_EVENT_MASK and cast AWTEvent to KeyEvent instead of MouseEvent.