简体   繁体   English

Thread.sleep()和mouseMove()的问题

[英]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). 我想在5秒(5000毫秒)后将光标从坐标(500,500)移到新坐标(1000,200)。 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). 但是,当我运行该程序时,光标仅显示到坐标(500,500),而没有移动到坐标(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). 您的代码每五秒钟将鼠标移至(1000,200),然后立即移至(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). 这意味着robot.mouseMove(MAX_X,MAX_Y)将在rob.mouseMove(1000,200)之后执行。

Simply remove the loop. 只需删除循环。 Also note, you only need one instance of the Robot class. 另请注意,您只需要一个Robot类实例。

It is useless to have two Robot object. 有两个Robot对象是没有用的。

Moreover you do not wait at all between rob.mouseMove(1000, 200) and robot.mouseMove(MAX_X, MAX_Y) . 此外,您根本不需要在robot.mouseMove(MAX_X, MAX_Y) rob.mouseMove(1000, 200)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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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