How to use java to move the mouse smoothly across the screen?

There is a MouseMove () method that causes the pointer to jump to that position I want to be able to move the mouse smoothly across the screen I need to write a method called mouseglide (), which uses start x, start y, end X, end y, the total time to be taken during taxiing and the number of steps to be taken during taxiing It should animate the mouse pointer by N steps from (start x, start y) to (end X, start y) Total coast down should take t milliseconds

I don't know how to start. Can you help me start this? Anyone can tell me what steps I need to take to make this problem effective

Solution

First, let's write an empty method with the same parameters as you defined in the problem

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

}

Next, let's create a robot object and calculate three pieces of information that will help you in your future calculations Don't forget to catch exceptions from instantiated 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 the X coordinate of the mouse at each slide Basically, it is the total moving distance divided into N steps Same as YY, except for the Y coordinate DT is the total coast down time, divided into N steps

Finally, build a loop that executes n times, moving the mouse closer to the final position each time (using the (DX, Dy) step) Hibernates the thread for DT milliseconds during each execution The greater your n, the smoother your glide

Final results:

public void mouseGlide(int x1,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();
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>