How would you determine if the mouse cursor is inside a JFrame in java?

How do you write a detection method if the mouse cursor is inside a JFrame in java? The method should return true if it is inside or false.

Thanks Andrew

+3
source share
4 answers

You must add a mouse listener and respond to mouseEntered-Event:

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

Assuming that the events mouseEnteredand mouseExitednot enough (it was for me as much as I wanted to avoid additional challenges mouseExitedwhen the mouse entered the border button within the panel), I came up with this short test to add to the beginning of the event handlers mouseEntered, and mouseExited:

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

JFrame mouseEntered mouseExited.

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
    }
});
+1

To expand the comment in the original publication, you can use the MouseInfo class to get the current location of the mouse. Then you compare this location with the borders of the frame to return the corresponding value.

+1
source

Source: https://habr.com/ru/post/1726190/


All Articles