开发者

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

Ho开发者_StackOverflow中文版w 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);
}


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.


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
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜