【问题标题】:How do I set the position of the mouse in Java?如何在 Java 中设置鼠标的位置?
【发布时间】:2010-05-31 04:10:43
【问题描述】:

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

【问题讨论】:

    标签: java user-interface swing mouse


    【解决方案1】:

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

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

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

    【讨论】:

    • @Daniel--自从你在这里回复已经有好几年了,但今天我找到了它,它解决了我几个月来因无意中单击鼠标重新定位文本光标而遇到的问题。在阅读您的评论之前,我很想只使用 Robot.mouseMove。奇怪的是,我刚刚开始使用多显示器设置!由于你使用了我不熟悉的类,我很震惊我所要做的就是复制你的代码,做一些导入,然后调用它。好工作!谢谢!!
    【解决方案2】:

    你需要使用Robot

    此类用于生成本机系统输入事件,用于测试自动化、自运行演示和其他需要控制鼠标和键盘的应用程序。 Robot 的主要目的是促进 Java 平台实现的自动化测试。

    使用类生成输入事件不同于将事件发布到 AWT 事件队列或 AWT 组件,因为事件是在平台的本机输入队列中生成的。例如,Robot.mouseMove 实际上会移动鼠标光标,而不是仅仅生成鼠标移动事件...

    【讨论】:

      【解决方案3】:

      【讨论】:

        【解决方案4】:

        查看Robot 类。

        【讨论】:

          【解决方案5】:

          代码本身如下:

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

          这段代码本身是不完整的,所以我建议将它放在一个方法中并调用类似“positionCursor(int row, int column)”的名称。

          这里是完整的代码(方法和代码):

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-01-04
            相关资源
            最近更新 更多