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
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
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.
So if I was writing pseudo code:
if(mouseInsideFrame==true)
frame.setVisible(true);
else
frame.setVisible(false);
What method would I use for the mouseInsideFrame in the if statement?