How do I set the position of the mouse in Java?

偶尔善良 提交于 2019-11-29 11:19:44

问题


I'm doing some Swing GUI work with Java, and I think my question is fairly straightforward; How does one set the position of the mouse?


回答1:


You need to use Robot

This class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations.

Using the class to generate input events differs from posting events to the AWT event queue or AWT components in that the events are generated in the platform's native input queue. For example, Robot.mouseMove will actually move the mouse cursor instead of just generating mouse move events...




回答2:


As others have said, this can be achieved using Robot.mouseMove(x,y). However this solution has a downfall when working in a multi-monitor situation, as the robot works with the coordinate system of the primary screen, unless you specify otherwise.

Here is a solution that allows you to pass any point based global screen coordinates:

public void moveMouse(Point p) {
    GraphicsEnvironment ge = 
        GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] gs = ge.getScreenDevices();

    // Search the devices for the one that draws the specified point.
    for (GraphicsDevice device: gs) { 
        GraphicsConfiguration[] configurations =
            device.getConfigurations();
        for (GraphicsConfiguration config: configurations) {
            Rectangle bounds = config.getBounds();
            if(bounds.contains(p)) {
                // Set point to screen coordinates.
                Point b = bounds.getLocation(); 
                Point s = new Point(p.x - b.x, p.y - b.y);

                try {
                    Robot r = new Robot(device);
                    r.mouseMove(s.x, s.y);
                } catch (AWTException e) {
                    e.printStackTrace();
                }

                return;
            }
        }
    }
    // Couldn't move to the point, it may be off screen.
    return;
}



回答3:


Robot.mouseMove(x,y)




回答4:


Check out the Robot class.




回答5:


The code itself is the following:

char escCode = 0x1B;
System.out.print(String.format("%c[%d;%df",escCode,row,column));

This code is incomplete by itself, so I recommend placing it in a method and calling it something like 'positionCursor(int row, int column)'.

Here is the code in full (method and code):

void positionCursor(int row, int column) {
        char escCode = 0x1B;
        System.out.print(String.format("%c[%d;%df",escCode,row,column));
}


来源:https://stackoverflow.com/questions/2941324/how-do-i-set-the-position-of-the-mouse-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!