简体   繁体   中英

Problems with Thread.sleep() and mouseMove()

I want to move my cursor from coordinates (500,500) to new coordinates (1000,200) after 5 seconds (5000 milliseconds). I want this event to occur every time the program runs, so that is why I have made a loop. But when I run the program, the cursor only appears to go to coordinates (500,500) and it does not move to coordinates (1000, 200). I need suggestions.

import java.awt.Robot;
import java.util.Random;

public class MouseMovers {

    public static  int SECONDS = 5000;
    public static  int MAX_Y =500;
    public static  int MAX_X =500;

    public static void main(String [] args) throws Exception {
        Robot robot = new Robot();
        Robot rob=new Robot();

        while (true) {
            robot.mouseMove(MAX_X, MAX_Y);
            Thread.sleep(SECONDS);
            rob.mouseMove(1000,200);
        }
    }
}

Every five seconds your code moves the mouse to (1000,200), and immediately afterwards to (500,500). Add another delay after the second move to make the mouse stay in that place for some time:

    while (true) {
        robot.mouseMove(MAX_X, MAX_Y);
        Thread.sleep(SECONDS);
        robot.mouseMove(1000, 200);
        Thread.sleep(SECONDS);
    }

BTW: you only need one Robot.

while (true) {
    robot.mouseMove(MAX_X, MAX_Y);
    Thread.sleep(SECONDS);
    rob.mouseMove(1000,200);
}

It's in a loop. This means robot.mouseMove(MAX_X, MAX_Y) will be executed just after rob.mouseMove(1000,200).

Simply remove the loop. Also note, you only need one instance of the Robot class.

It is useless to have two Robot object.

Moreover you do not wait at all between rob.mouseMove(1000, 200) and robot.mouseMove(MAX_X, MAX_Y) .

Then the correct code should be :

import java.awt.Robot;
import java.util.Random;

public class MouseMovers {

    public static  int MILLISECONDS = 5000;
    public static  int MAX_Y = 500;
    public static  int MAX_X = 500;
    public static  int NEW_MAX_X = 1000;
    public static  int NEW_MAX_Y = 2000;

    public static void main(String [] args) throws Exception {
        Robot robot = new Robot();

        while (true) {
            robot.mouseMove(MAX_X, MAX_Y);
            Thread.sleep(MILLISECONDS);
            robot.mouseMove(NEW_MAX_X, NEW_MAX_Y);
            Thread.sleep(MILLISECONDS);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM