既然你跟你說一個「廣場」的工作,你可能想使用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);
}
}
}
完成這是一個基本的演示。
您可能需要添加負/外的範圍值檢查等,以便它不會嘗試單擊關閉屏幕。
你有興趣知道,如果'''java.util.Random'''存在?是的,它確實。產生'''xmin'''和'''xmax'''(含)之間'''x'''座標:'''X = XMIN + r.nextInt(XMAX-XMIN + 1)''' – tevemadar