我试图找到一种方法将光标发送到屏幕上的像素。在这里,我有一些代码可以将它发送到特定的位置:
package JavaObjects;
import java.awt.AWTException;
import java.awt.Robot;
public class MCur {
public static void main(String args[]) {
try {
// The cursor goes to these coordinates
int xCoord = 500;
int yCoord = 500;
// This moves the cursor
Robot robot = new Robot();
robot.mouseMove(xCoord, yCoord);
} catch (AWTException e) {}
}
}
是否有某些方法,使用类似的代码,我可以建立一个范围而不是一个特定的点,这样光标就会到达已建立的方块的某个随机部分?
答案 0 :(得分:2)
由于你正在使用" Square",你可能想要使用java.awt.Rectangle类,如果你点击按钮,这特别有用您可以定义按钮边界而不是点。
对于随机半径,可以使用java.util.Random
轻松完成import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.util.Random;
public class MoveMouse {
private static final Robot ROBOT;
private static final Random RNG;
public static void main(String[] args) {
// grab the screen size
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
// Equivalent to 'new Rectangle(0, 0, screen.width, screen.height)'
Rectangle boundary = new Rectangle(screen);
// move anywhere on screen
moveMouse(boundary);
}
public static void moveMouse(int x, int y, int radiusX, int radiusY) {
Rectangle boundary = new Rectangle();
// this will be our center
boundary.setLocation(x, y);
// grow the boundary from the center
boundary.grow(radiusX, radiusY);
moveMouse(boundary);
}
public static void moveMouse(Rectangle boundary) {
// add 1 to the width/height, nextInt returns an exclusive random number (0 to (argument - 1))
int x = boundary.x + RNG.nextInt(boundary.width + 1);
int y = boundary.y + RNG.nextInt(boundary.height + 1);
ROBOT.mouseMove(x, y);
}
// initialize the robot/random instance once when the class is loaded
// and throw an exception in the unlikely scenario when it can't
static {
try {
ROBOT = new Robot();
RNG = new Random();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
这是一个基本的演示。
您可能需要添加负值/超出范围的值检查等,以便它不会尝试点击屏幕。