总结:我正在创建一个程序,将用户的鼠标移动到预定的屏幕坐标。程序通过坐标移动鼠标,以模拟人体运动。问题是程序只将鼠标移动到其中一个坐标(无论哪个到达第一个坐标)并且在停止后立即移动。我需要它将鼠标移动到正确的坐标。
import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
import java.awt.Robot;
import java.util.Random;
public class MouseMover implements Runnable {
Robot robot;
Random random = new Random();
int dX, // destination x-coord
dY, // destination y-coord
cX,
cY;
PointerInfo pointerInfo;
Point point;
public MouseMover(int mX, int mY) throws AWTException {
robot = new Robot();
dX = mX;
dY = mY;
}
@Override
public void run() {
pointerInfo = MouseInfo.getPointerInfo();
point = pointerInfo.getLocation();
cX = (int) point.getX(); // get current mouse pointer's x-coord
cY = (int) point.getY(); // get current mouse pointer's y-coord
System.out.println("Current: (" + cX + ", " + cY + ")");
System.out.println("Destination: (" + dX + ", " + dY + ")");
while (cX != dX && cY != dY) { // move loop: move mouse pointer until at predetermined point
if (cX < dX) {
cX++;
} else if (cX > dX) {
cX--;
} else {
}
if (cY < dY) {
cY++;
} else if (cY > dY) {
cY--;
} else {
}
robot.mouseMove(cX, cY); // move mouse pointer to next coordinate
System.out.println("Current: (" + cX + ", " + cY + ")");
try {
Thread.sleep((int) (Math.random() * ((15 - 1) + 1)) + 1);
} catch (InterruptedException ex) {
}
}
}
}
主类:
import java.awt.AWTException;
public class Main {
public static void main(String[] args) {
try {
new Thread(new MouseMover(200, 200)).start();
} catch (AWTException ex) {
ex.printStackTrace();
}
}
}
答案 0 :(得分:2)
问题是程序只将鼠标移动到其中一个坐标(无论哪个到达第一个坐标)并且在停止后立即移动。我需要它将鼠标移动到正确的坐标。
那么当任何坐标到达目的地时,为什么要停止它:cX != dX && cY != dY
?您应该使用||
代替&&
。