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();
}
}
}
}
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023
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.
Also, this code was EXTREMELY helpful, I will be sure to support you when I have the time!
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 callMouseInfo.getPointerInfo()
we actually get an instance ofPointerInfo
defined in theMouseInfo
object. An then we call thegetLocation()
of this object which return an object of typePoint
.That makes sense,
getLocation()
is aPointerInfo
method. I kind of guessed that an instance ofPointerInfo
was created somewhere, but I wasn’t too sure.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 thejava.awt.PointerInfo
class is created.