tags:

views:

165

answers:

4

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

+1  A: 

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

JFrame.addMouseListener( new MouseAdapter() {
    public void mouseEntered( MouseEvent e ) {
        // your code here
    }
} );
tangens
Won't work if other components have MouseListeners, because as soon as the mouse goes over other components a mouseExited() event will be generated.
camickr
A: 

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
    }
});
Alex
A: 

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.

camickr
A: 

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?

Andrew