MouseListener on JFrame

12,388

Solution 1

You can get all events and check if their source is a component in the JFrame.

See Toolkit.addAWTEventListener

Solution 2

There is an invisible component that overlays the whole GUI, the "glass pane". You can attach your listeners to that. Example:

JFrame frame = new JFrame();
Component glassPane = frame.getGlassPane();
glassPane.addMouseListener(myListener);

If you want your intercepted events to pass through to the underlying components, you can redispatch them. For example:

public void mouseMoved(MouseEvent e) {
    redispatchMouseEvent(e, false);
}

Solution 3

Because the contents ( probably a JPanel ) are "shadowing" and consuming the events and they don't reach the JFrame.

What you can do is to add the same listener to all the children. There should be a better way though.

Solution 4

An alternative to AWTEventListener is to push an EventQueue. This has the advantage that applets and WebStart application can do this.

Share:
12,388
Mohammad Taha
Author by

Mohammad Taha

Android geek, TDD nut, International Speaker, ex Shazamer, currently the Principal Software Engineer for Apps at ASOS. Noti.st | Twitter | LinkedIn | GitHub

Updated on August 14, 2022

Comments

  • Mohammad Taha
    Mohammad Taha almost 2 years

    I want to be notified of mouse events (specifically the mouse entered and exited events) on my JFrame. But when i add a mouselistener to it i get the events on the borders of the frame not the entire frame with it's contents.

    Any ideas as to why?

    EDIT : Or at least do you have an alternative? I want a "gloabal" way to catch mouse events on the JFrame. Maybe a mouselistener is not the answer.

  • Mohammad Taha
    Mohammad Taha over 14 years
    i would have to enable it. this would prevent the components beneath to receive events
  • SingleShot
    SingleShot over 14 years
    You can redispatch. See my revised answer.
  • Mohammad Taha
    Mohammad Taha over 14 years
    There is entire issue when enabling the glass pane. It is best described in Filthy Rich Clients. You need to foresee all the problems and rectify them. For instance you also need to account for key events, mouse cursor changes among other things. I'm looking for a ready made solution. something that was designed to notify on mouse events on a frame level.
  • PhiLho
    PhiLho almost 13 years
    I must agree with @Sawas, alas. I implemented the code in codeidol.com/java/swing/Rendering/Create-a-Global-Right-Clic‌​k (similar to what you show) but while it worked quite fine, I had issues with underlying L&F components like split bars (no cursor change over them and drawing fails when going too fast) and scrollbar buttons (no scrollbar move).