java.awt.Robot 類提供了模擬鼠標移動、點擊、鍵盤按鍵等底層輸入事件的能力。它常用於自動化測試、演示程式或輔助工具開發。一旦獲取 Robot 實例,即可通過程式碼模擬使用者的各種操作。
以下程式碼展示如何模擬鍵盤輸入「HI CAOER」字串。執行後有 5 秒延遲,供使用者切換到記事本等編輯器:
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class RobotExp {
public static void main(String[] args) {
try {
Robot robot = new Robot();
// 延遲 5 秒,方便切換視窗
robot.delay(5000);
// 模擬按鍵按下(需配合 release 才算完整按鍵)
robot.keyPress(KeyEvent.VK_H);
robot.keyPress(KeyEvent.VK_I);
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyPress(KeyEvent.VK_C);
robot.keyPress(KeyEvent.VK_A);
robot.keyPress(KeyEvent.VK_O);
robot.keyPress(KeyEvent.VK_E);
robot.keyPress(KeyEvent.VK_R);
} catch (AWTException e) {
e.printStackTrace();
}
}
}
網友改進版本封裝了 pressKey 和 pressKeyWithShift 方法,確保每個按鍵都正確釋放,並支援大寫字母輸入:
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.IOException;
public class RobotExp {
public static void pressKey(Robot robot, int keyvalue) {
robot.keyPress(keyvalue);
robot.keyRelease(keyvalue);
}
public static void pressKeyWithShift(Robot robot, int keyvalue) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(keyvalue);
robot.keyRelease(keyvalue);
robot.keyRelease(KeyEvent.VK_SHIFT);
}
public static void closeApplication(Robot robot) {
// Alt+F4 關閉視窗(Windows)
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_F4);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_F4);
// 確認關閉對話框(按 N)
robot.keyPress(KeyEvent.VK_N);
robot.keyRelease(KeyEvent.VK_N);
}
public static void main(String[] args) throws IOException {
try {
Robot robot = new Robot();
// 自動啟動記事本
Runtime.getRuntime().exec("notepad");
robot.delay(3000);
for (int i = 0; i < 100; i++) {
pressKeyWithShift(robot, KeyEvent.VK_H); // H
pressKey(robot, KeyEvent.VK_I); // i
pressKey(robot, KeyEvent.VK_SPACE); // 空格
pressKeyWithShift(robot, KeyEvent.VK_I); // I
pressKey(robot, KeyEvent.VK_SPACE);
pressKey(robot, KeyEvent.VK_A);
pressKey(robot, KeyEvent.VK_M);
pressKey(robot, KeyEvent.VK_SPACE);
pressKey(robot, KeyEvent.VK_T);
pressKey(robot, KeyEvent.VK_H);
pressKey(robot, KeyEvent.VK_E);
pressKey(robot, KeyEvent.VK_SPACE);
pressKey(robot, KeyEvent.VK_J);
pressKey(robot, KeyEvent.VK_A);
pressKey(robot, KeyEvent.VK_V);
pressKey(robot, KeyEvent.VK_A);
pressKey(robot, KeyEvent.VK_SPACE);
pressKey(robot, KeyEvent.VK_R);
pressKey(robot, KeyEvent.VK_O);
pressKey(robot, KeyEvent.VK_B);
pressKey(robot, KeyEvent.VK_O);
pressKey(robot, KeyEvent.VK_T);
pressKey(robot, KeyEvent.VK_ENTER); // 換行
}
closeApplication(robot);
} catch (AWTException e) {
e.printStackTrace();
}
}
}