首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Java中设置鼠标的位置?

如何在Java中设置鼠标的位置?
EN

Stack Overflow用户
提问于 2010-05-31 12:10:44
回答 4查看 35.2K关注 0票数 22

我正在用Java做一些Swing GUI工作,我想我的问题相当简单;如何设置鼠标的位置?

EN

回答 4

Stack Overflow用户

发布于 2012-05-19 20:42:16

正如其他人所说,这可以使用Robot.mouseMove(x,y)来实现。但是,此解决方案在多显示器情况下工作时会出现问题,因为机器人使用主屏幕的坐标系工作,除非您另行指定。

这是一个允许你传递任何基于全局屏幕坐标的点的解决方案:

代码语言:javascript
复制
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;
}
票数 25
EN

Stack Overflow用户

发布于 2010-05-31 12:34:54

票数 8
EN

Stack Overflow用户

发布于 2010-05-31 12:14:11

查看Robot类。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2941324

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档