Search code examples
javamouseawtrobot

Java: Robot Mouse Move Unknown Error


Summary: I am creating a program that moves the user's mouse to a predetermined, on-screen coordinate. The program shifts the mouse, coordinate by coordinate, to simulate human motion. The issue is that the program only moves the mouse to one of the coordinates (whichever it reaches first) and immediately after stops. I need it to shift the mouse to the correct coordinate.

import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
import java.awt.Robot;
import java.util.Random;

public class MouseMover implements Runnable {

    Robot robot;
    Random random = new Random();

    int dX, // destination x-coord
            dY, // destination y-coord
            cX,
            cY;

    PointerInfo pointerInfo;
    Point point;

    public MouseMover(int mX, int mY) throws AWTException {
        robot = new Robot();

        dX = mX;
        dY = mY;
    }

    @Override
    public void run() {
        pointerInfo = MouseInfo.getPointerInfo();
        point = pointerInfo.getLocation();

        cX = (int) point.getX(); // get current mouse pointer's x-coord
        cY = (int) point.getY(); // get current mouse pointer's y-coord

        System.out.println("Current: (" + cX + ", " + cY + ")");

        System.out.println("Destination: (" + dX + ", " + dY + ")");

        while (cX != dX && cY != dY) { // move loop: move mouse pointer until at predetermined point
            if (cX < dX) {
                cX++;
            } else if (cX > dX) {
                cX--;
            } else {
            }

            if (cY < dY) {
                cY++;
            } else if (cY > dY) {
                cY--;
            } else {
            }

            robot.mouseMove(cX, cY); // move mouse pointer to next coordinate

            System.out.println("Current: (" + cX + ", " + cY + ")");

            try {
                Thread.sleep((int) (Math.random() * ((15 - 1) + 1)) + 1);
            } catch (InterruptedException ex) {
            }
        }
    }
}

Main Class:

import java.awt.AWTException;

public class Main {
    public static void main(String[] args) {
        try {
            new Thread(new MouseMover(200, 200)).start();
        } catch (AWTException ex) {
            ex.printStackTrace();
        }
    }
}

Solution

  • The issue is that the program only moves the mouse to one of the coordinates (whichever it reaches first) and immediately after stops. I need it to shift the mouse to the correct coordinate.

    Then why do you stop it when any coordinate reaches the destination: cX != dX && cY != dY? You should be using || instead of &&.