How to move a mouse smoothly throughout the screen by using java?

久未见 提交于 2019-11-28 09:31:40

To start off, let's just write out an empty method where the parameters are as you defined in your question.

public void mouseGlide(int x1, int y1, int x2, int y2, int t, int n) {

}

Next, let's create a Robot object and also calculate 3 pieces of information that'll help your future calculations. Don't forget to catch the exception from instantiating Robot.

Robot r = new Robot();
double dx = (x2 - x1) / ((double) n);
double dy = (y2 - y1) / ((double) n);
double dt = t / ((double) n);

dx represents the difference in your mouse's x coordinate everytime it moves while gliding. Basically it's the total move distance divided into n steps. Same thing with dy except with the y coordinate. dt is the total glide time divided into n steps.

Finally, construct a loop that executes n times, each time moving the mouse closer to the final location (taking steps of (dx, dy)). Make the thread sleep for dt milliseconds during each execution. The larger your n is, the smoother the glide will look.


Final result:

public void mouseGlide(int x1, int y1, int x2, int y2, int t, int n) {
    try {
        Robot r = new Robot();
        double dx = (x2 - x1) / ((double) n);
        double dy = (y2 - y1) / ((double) n);
        double dt = t / ((double) n);
        for (int step = 1; step <= n; step++) {
            Thread.sleep((int) dt);
            r.mouseMove((int) (x1 + dx * step), (int) (y1 + dy * step));
        }
    } catch (AWTException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

For all those who have been struggling with the programming as I did before, this is how you implement this method and use it correctly:

    public class gliding_the_mouse {

    public void mouseGlide(int x1, int y1, int x2, int y2, int t, int n) {
try {
    Robot r = new Robot();
    double dx = (x2 - x1) / ((double) n);
    double dy = (y2 - y1) / ((double) n);
    double dt = t / ((double) n);
    for (int step = 1; step <= n; step++) {
        Thread.sleep((int) dt);
        r.mouseMove((int) (x1 + dx * step), (int) (y1 + dy * step));
    }
} catch (AWTException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
} }    
public static void main (String[] args) { // program initialization
gliding_the_mouse x = new gliding_the_mouse(); // we declare what are we gonna use

x.mouseGlide(400,500,700,700,5000,10000); // the smaller the time value, the faster the mouse glides. 

} } // P.s I am new to StackOverflow, so I am not particular experienced with it, sorry for ugly design
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!