Home > Software > Tip: Mouse pointer in Java

Tip: Mouse pointer in Java


Repetition is the mother of all learning!
Even you knew already or it is old news to you, I feel like repeating this tip: how to handle mouse pointer in Java. For doing this in a framework like Swing or SWT you have all these kind of mouse events associated with the components, but what I’m interested in is a more global view. To get (and set!) the mouse coordinates at the entire desktop level.
For getting the mouse coordinates you have the MouseInfo class. For x coordinate just call MouseInfo.getPointerInfo().getLocation().getX(). Similarly, for y is MouseInfo.getPointerInfo().getLocation().getY().
On the other hand for setting the mouse coordinates on screen, you have the Robot class and its mouseMove method.
Now putting all together and write a method that moves the mouse with a certain amount on screen:

void mouseRelMove(int dx, int dy) {
    new Robot().mouseMove(MouseInfo.getPointerInfo().getLocation().getX() + dx, MouseInfo.getPointerInfo().getLocation().getY() + dy);
}

Now you can play with your mouse. But carefully, not to get it (or you!) dizzy🙂.

Categories: Software Tags:
  1. Iain Elder
    September 26, 2010 at 2:29 pm

    I didn’t know this before. Now I can make that drunk mouse program to confuse my friends😉 Cheers!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: