Java - Getting the mouse cursor location (current mouse position)

Java mouse cursor location FAQ: How do I get the location of the mouse (mouse cursor) in Java?

I just ran into this problem in my Java Robot programming, and the short answer is, to get the current mouse cursor location/position, use the getPointerInfo method of the java.awt.MouseInfo class, like this:

Point p = MouseInfo.getPointerInfo().getLocation();

After that call you can access the mouse x and y coordinates as int values like this:

int x = p.x;
int y = p.y;

If you're writing a normal Java/Swing application, you'll probably want to use the MouseListener or MouseMotionListener interfaces (or their corresponding "adapter" classes), but those are limited to only giving you the mouse coordinates when the mouse is within the borders of your application. The MouseInfo class doesn't have that limitation, and can give you the mouse coordinates regardless of where the mouse pointer is position on the screen.

I hope this Java mouse location tip is helpful. The big trick about getting the mouse cursor location in Java was learning about the Java MouseInfo class.