How do I get the location of mouse pointer?

MouseInfo provides methods for getting information about the mouse, such as mouse pointer location and the number of mouse buttons.

package org.kodejava.awt;

import java.awt.*;

public class MouseInfoDemo {
    public static void main(String[] args) {
        int i = 0;
        while (i < 10) {
            // Get the location of our mouse x and y coordinate using
            // the PointerInfo.getLocation() method which return an 
            // instance of Point.
            Point location = MouseInfo.getPointerInfo().getLocation();
            double x = location.getX();
            double y = location.getY();

            System.out.println("x = " + x);
            System.out.println("y = " + y);

            try {
                Thread.sleep(1000);
                i++;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
Wayan

5 Comments

  1. I noticed you say “Get the location of our mouse x and y coordinate from the PointerInfo location object.” And I am no expert coder, but I am curious (and am taking a computer science class in high school where we learn Java) but is the PointerInfo object even used? You use the Point class in instantiate a MouseInfo object.

    Reply
    • Hi Vladimir,

      I cleared up the comment in the code that might confuse you. The PointerInfo object is still called in this process. When we call MouseInfo.getPointerInfo() we actually get an instance of PointerInfo defined in the MouseInfo object. An then we call the getLocation() of this object which return an object of type Point.

      Reply
  2. That makes sense, getLocation() is a PointerInfo method. I kind of guessed that an instance of PointerInfo was created somewhere, but I wasn’t too sure.

    Reply
    • Hello Vladimir,

      You can always take a look at the source code available in the JDK distribution, the source is included. Take a peek at the java.awt.MouseInfo class, you will see how the java.awt.PointerInfo class is created.

      Reply

Leave a Reply to VladimirCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.