Java robot.mouseMove(x, y) not producing correct results

后端 未结 2 1306
不知归路
不知归路 2021-01-05 03:27

I have recently been trying to automate a program I made and I have run into a problem, robot.mouseMove(100, 100) doesn\'t send the mouse to 100, 100.

I made this si

相关标签:
2条回答
  • 2021-01-05 03:35

    Probably you do not need to point at exact pixel, and you may allow a bit difference. So, allow it and it will take much less tries. I have two 1080 monitors 100% scale and use a loop to check position with a limit of 100 tries. Some time it reaches the limit without right positioning, in my case. So I modified a loop to allow a difference in 3 points (I do not need really exact positioning) and now it moves mouse near the right spot in less than 10 attempts.

            for (int ntry = 0; ntry < moveTryMax; ntry++) {
                bot.mouseMove(paramVO.getX(), paramVO.getY());
                Point testPoint = MouseInfo.getPointerInfo().getLocation();
    
                if (Math.abs(testPoint.x - paramVO.getX()) <= pointsDeltaMax && Math.abs(testPoint.y - paramVO.getY()) <= pointsDeltaMax) {
                    if (showMessages) {
                        System.out.println("N try: " + ntry);
                    }
                    break;
                }
            }
    
    0 讨论(0)
  • 2021-01-05 03:47

    The JDK Bug website says a current workaround is to call the function in a loop until the mouse moved to the right space. You could use a function like this:

    public static void moveMouse(int x, int y, int maxTimes, Robot screenWin) {
        for(int count = 0;(MouseInfo.getPointerInfo().getLocation().getX() != x || 
                MouseInfo.getPointerInfo().getLocation().getY() != y) &&
                count < maxTimes; count++) {
            screenWin.mouseMove(x, y);
        }
    }
    

    Max times is there to stop an infinite loop in case something happens. Usually 4-5 times is good enough for me.

    0 讨论(0)
提交回复
热议问题