2017-10-06 36 views
0

我試圖找到一種方法將光標發送到屏幕上的像素的正方形廣場。在這裏,我有一些代碼,可以將它發送到特定位置:發送光標像素

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

你有興趣知道,如果'''java.util.Random'''存在?是的,它確實。產生'''xmin'''和'''xmax'''(含)之間'''x'''座標:'''X = XMIN + r.nextInt(XMAX-XMIN + 1)''' – tevemadar

回答

2

既然你跟你說一個「廣場」的工作,你可能想使用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); 
     } 
    } 

} 

完成這是一個基本的演示。

您可能需要添加負/外的範圍值檢查等,以便它不會嘗試單擊關閉屏幕。

+0

感謝您的幫助!我得到它來編譯,但是當我去運行它時,它說沒有一個具有接受String []的靜態void main方法的類。在我上面包含的代碼,我用行「公共靜態無效的主要(字符串ARGS []){」來解決這個同樣的問題,但是當我在這裏使用的線,我收到了一堆新的錯誤,如「插入枚舉標識符「在」靜態{「行。你會碰巧知道我能做什麼嗎?我知道這些事情很難在評論中診斷,如果你不知道你的頭頂是好的 – RealFL

+0

我已經添加了類進口/課堂主體/主要方法,但我強烈建議更專注於語法和基本語言特性,然後再嘗試實際做出任何事情。 – Caleb