131

I would like to simulate a natural mouse movement in Java (going from here to there pixel by pixel). To do that I need to know the starting coordinates.

I've found the method event.getX() and event.getY() but I need an event...

How can I know the positions without doing anything (or something not visible)?

Thank you

asteri
  • 11,402
  • 13
  • 60
  • 84
Martin Trigaux
  • 5,311
  • 9
  • 45
  • 58

10 Answers10

245

MouseInfo.getPointerInfo().getLocation() might be helpful. It returns a Point object corresponding to current mouse position.

Martin Quinson
  • 1,347
  • 8
  • 16
vpram86
  • 5,860
  • 4
  • 28
  • 40
  • 52
    `getPointerInfo().getLocation()` returns the position relative to the screen. If you want the position relative to your component (like given by MouseListeners) you can subtract `yourComponent.getLocationOnScreen()` from it. – Thomas Ahle Jan 10 '12 at 10:43
  • 3
    +1 `Container.getMousePosition()` can some times return `null` if the mouse is moving too fast, using this avoids the issue. – Emily L. Feb 07 '14 at 21:21
  • 13
    In addition to what @ThomasAhle said, you can avoid implementing it yourself, by using an already implemented convinience method: `SwingUtilities.convertPointFromScreen(MouseInfo.getPointerInfo().getLocation(), component)` – Andrei Vajna II Aug 29 '14 at 10:48
  • 2
    Note `MouseInfo.getPointerInfo()` can return null when there is no mouse or in some multimon setups. – NateS Nov 04 '15 at 06:07
  • 3
    Note that `SwingUtilities.convertPointFromScreen(..)` converts the first argument in-place and doesn't return anything, so it needs to be written a bit differently relative to @AndreiVajnaII comment so that we can get hold of the `Point` object. – Evgeni Sergeev Sep 21 '16 at 03:29
  • Is there an event to which one could register a listener to get notified the mouse moved? – ed22 Jan 06 '21 at 01:22
46
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
int x = (int) b.getX();
int y = (int) b.getY();
System.out.print(y + "jjjjjjjjj");
System.out.print(x);
Robot r = new Robot();
r.mouseMove(x, y - 50);
CSchulz
  • 10,882
  • 11
  • 60
  • 114
Nauman Khalid
  • 852
  • 9
  • 15
12

In SWT you need not be in a listener to get at the mouse location. The Display object has the method getCursorLocation().

In vanilla SWT/JFace, call Display.getCurrent().getCursorLocation().

In an RCP application, call PlatformUI.getWorkbench().getDisplay().getCursorLocation().

For SWT applications, it is preferable to use getCursorLocation() over the MouseInfo.getPointerInfo() that others have mentioned, as the latter is implemented in the AWT toolkit that SWT was designed to replace.

stevorino
  • 121
  • 1
  • 3
8
import java.awt.MouseInfo;
import java.awt.GridLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

import javax.swing.*;

public class MyClass {
  public static void main(String[] args) throws InterruptedException{
    while(true){
      //Thread.sleep(100);
      System.out.println("(" + MouseInfo.getPointerInfo().getLocation().x + 
              ", " + 
              MouseInfo.getPointerInfo().getLocation().y + ")");
    }
  }
}
Srb
  • 219
  • 3
  • 13
7
import java.awt.MouseInfo;
import java.util.concurrent.TimeUnit;

public class Cords {

    public static void main(String[] args) throws InterruptedException {

        //get cords of mouse code, outputs to console every 1/2 second
        //make sure to import and include the "throws in the main method"

        while(true == true)
        {
        TimeUnit.SECONDS.sleep(1/2);
        double mouseX = MouseInfo.getPointerInfo().getLocation().getX();
        double mouseY = MouseInfo.getPointerInfo().getLocation().getY();
        System.out.println("X:" + mouseX);
        System.out.println("Y:" + mouseY);
        //make sure to import 
        }

    }

}
Sardar Usama
  • 19,536
  • 9
  • 36
  • 58
Josh McQuinn
  • 79
  • 1
  • 1
5

Try looking at the java.awt.Robot class. It allows you to move the mouse programatically.

Jeff Storey
  • 56,312
  • 72
  • 233
  • 406
2

If you're using Swing as your UI layer, you can use a Mouse-Motion Listener for this.

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
2

I am doing something like this to get mouse coordinates using Robot, I use these coordinates further in few of the games I am developing:

public class ForMouseOnly {
    public static void main(String[] args) throws InterruptedException {
        int x = MouseInfo.getPointerInfo().getLocation().x;
        int y = MouseInfo.getPointerInfo().getLocation().y;
        while (true) {

            if (x != MouseInfo.getPointerInfo().getLocation().x || y != MouseInfo.getPointerInfo().getLocation().y) {
                System.out.println("(" + MouseInfo.getPointerInfo().getLocation().x + ", "
                        + MouseInfo.getPointerInfo().getLocation().y + ")");
                x = MouseInfo.getPointerInfo().getLocation().x;
                y = MouseInfo.getPointerInfo().getLocation().y;
            }
        }
    }
}
Varun Ved
  • 339
  • 3
  • 6
0

In my scenario, I was supposed to open a dialog box in the mouse position based on a GUI operation done with the mouse. The following code worked for me:

    public Object open() {
    //create the contents of the dialog
    createContents();
    //setting the shell location based on the curent position
    //of the mouse
    PointerInfo a = MouseInfo.getPointerInfo();
    Point pt = a.getLocation();
    shellEO.setLocation (pt.x, pt.y);

    //once the contents are created and location is set-
    //open the dialog
    shellEO.open();
    shellEO.layout();
    Display display = getParent().getDisplay();
    while (!shellEO.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    return result;
}
sudipn
  • 619
  • 5
  • 14
-1

If you're using SWT, you might want to look at adding a MouseMoveListener as explained here.

Topher Fangio
  • 20,372
  • 15
  • 61
  • 94
  • 4
    but the Listener is executed only if I do something (move, click) with my mouse, right ? The first thing I need before moving it is to know the starting position – Martin Trigaux Sep 17 '09 at 14:05