简体   繁体   中英

how would you detect if the mouse cursor is inside a JFrame in java?

How would you write a method to detect if the mouse cursor is inside a JFrame in java? The method should return true if it is inside or else false.

Thanks, Andrew

Assuming that the mouseEntered and mouseExited events are not sufficient (this was the case for me as I wanted to avoid extra calls to mouseExited when the mouse cursor entered a button's bounds within a panel), I came up with this short check to add to the beginning of my mouseEntered and mouseExited event handlers:

public static boolean isMouseWithinComponent(Component c)
{
    Point mousePos = MouseInfo.getPointerInfo().getLocation();
    Rectangle bounds = c.getBounds();
    bounds.setLocation(c.getLocationOnScreen());
    return bounds.contains(mousePos);
}

You should add a mouse listener and react to the mouseEntered-Event:

JFrame.addMouseListener( new MouseAdapter() {
    public void mouseEntered( MouseEvent e ) {
        // your code here
    }
} );

Add a mouse listener to your JFrame, and look for mouseEntered and mouseExited events.

frame.addMouseListener(new MouseListener() {
    public void mouseEntered(java.awt.event.MouseEvent evt) {
        // do your action here
    }

    public void mouseExited(java.awt.event.MouseEvent evt) {
        // do your action here
    }
});

To expand on the comment in the original posting you can use the MouseInfo class to get the current location of the mouse. Then you compare this location with the bounds on the frame to return the appropriate value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM