Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

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

There is a mouseMove()method that makes the pointer jump to that location. I want to be able to make the mouse move smoothly throughout the screen. I need to write a method named mouseGLide() which takes a start x, start y, end x, end y, the total time the gliding should take, and the number of steps to make during the glide. It should animate the mouse pointer by moving from (start x, start y) to (end x, start y) in n steps. The total glide should take t milliseconds.

I don't know how to get started can anyone help me get started on this? Can anyone just tell me what steps I need to do in order to make this problem work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...