tags:

views:

976

answers:

5

I have a JFrame that has a large number of changing child components. (Many layers) Is there any way to add a listener for all mouse events? Something like KeyEventDispatcher?

A: 

Implement all mouse-related listeners in a class, and register that class as the handler for all mouse related events

Mouse Related interfaces would be

MouseListener MouseMotionListener MouseWheelListener

Midhat
A: 

You have to use JFrame's glassPane: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JFrame.html#getGlassPane()

Just get the glass pane of a JFrame with frm.getGlassPane() and use addMouseListener() on it to capture all mouse event inside the window.

Vitaly Polonetsky
A: 

You might want to implement a subclass of MouseAdapter, an abstract class that provides empty implementations of all of the methods defined in the Mouse*Listener Interfaces. Once you do that, you can register it with your child components as a MouseListener when they are created. As you indicate that your components are 'changing,' you will want to make sure the you also unregister your listener if you hope to release your components during the lifecycle of your JFrame.

akf
MouseInputAdapter - MouseAdapter is only an implementation for MouseListener (clicks, no motion or scroll wheel).
Nate
Nate, thanks for the reply. Looking at the code, I see that MouseAdapter implements all three interfaces.
akf
+3  A: 

You could add a GlassPane over your entire JFrame, add a MouseInputAdapter to it to grab all possible mouse events, and then use [SwingUtilities.getDeepestComponentAt()][3] to get the actual component and [SwingUtilities.convertMouseEvent()][4] to delegate the mouse event from the glass pane to the actual component.

However, I'm not sure of the performance impact of this - unlike KeyEventDispatcher, which just needs to fire an event whenever a key is pressed, multiple events are generated as the user moves the mouse - and unlike KeyEventDispatcher, you need to re-send the event to the lower component for it to handle it.

(Sorry - stackoverflow isn't handling the links to the SwingUtilities methods correctly... links are showing below rather than in the text.)

[3]: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/SwingUtilities.html#getDeepestComponentAt(java.awt.Component, int, int) [4]: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/SwingUtilities.html#convertMouseEvent(java.awt.Component, java.awt.event.MouseEvent, java.awt.Component)

Nate
+4  A: 

Use an AWTEventListener to filter out the MouseEvents:

long eventMask = AWTEvent.MOUSE_MOTION_EVENT_MASK + AWTEvent.MOUSE_EVENT_MASK;
Toolkit.getDefaultToolkit().addAWTEventListener( new AWTEventListener()
{
    public void eventDispatched(AWTEvent e)
    {
     System.out.println(e);
    }
}, eventMask);
camickr
+1 better answer than mine.
Nate
This is not allowed in unsigned applets
flamingpenguin