2010-11-20 109 views
18

我想製作一個應用程序,用於測量光標與組件中心的距離,然後將光標移回中心(與大多數PC視頻遊戲一樣)。有沒有人有什麼建議?在Java中移動光標

回答

29

機器人類可以爲你做的伎倆。這裏是移動鼠標光標的示例代碼:

try { 
    // These coordinates are screen coordinates 
    int xCoord = 500; 
    int yCoord = 500; 

    // Move the cursor 
    Robot robot = new Robot(); 
    robot.mouseMove(xCoord, yCoord); 
} catch (AWTException e) { 
} 
+0

謝謝您的打氣!這當然做到了。 :3 – Supuhstar 2010-11-20 11:07:05

3

嗨,這將只是增加。我使用Raspberry PI很多,所以我不得不學習如何優化我的代碼,這會縮短很多。

try { 
    //moves mouse to the middle of the screen 
    new Robot().mouseMove((int) Toolkit.getDefaultToolkit().getScreenSize().getWidth()/2, (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight()/2); 
    //remember to use try-catch block (always, and remember to delete this) 
} catch (AWTException e) { 
    e.printStackTrace(); 
} 

不要忘記導入:

import java.awt.*; 
+0

我很困惑......你說的是將你的源代碼存儲在Pi上嗎?還是這樣神奇地使編譯的文件更小?如果後者,爲什麼刪除評論的指示? – Supuhstar 2015-09-18 15:41:17

+0

那麼變量越少越好,你想使它非常緊湊,所以它不會在RAM上產生溢出。 – 2015-09-18 15:46:56

+1

但無論如何,它會使您的代碼產生臨時變量。點鏈是句法糖,但最後,每個方法的返回值必須保存並跟蹤到某處 – Supuhstar 2015-09-18 16:40:29