Java.awt.Robot 類用於控制鼠標和鍵盤。一旦你獲得這種控制,你可以經過你的Java代碼作與鼠標和鍵盤任何類型的操做。這個類一般用於自動化測試。下面的代碼樣例將向您展現Robot類如何處理鍵盤事件。若是你運行此代碼,並打開notepad,您將在notepad中看到HI CAOERjava
package test; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import java.io.IOException; /** * * @time 2012/05/07 * @author SUN * Robot 自動化 */ 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) { // pressKey(robot, KeyEvent.VK_ALT); // pressKey(robot, KeyEvent.VK_F4); robot.keyPress(KeyEvent.VK_ALT); robot.keyPress(KeyEvent.VK_F4); robot.keyRelease(KeyEvent.VK_ALT); robot.keyRelease(KeyEvent.VK_F4); //for linux. // robot.keyPress(KeyEvent.VK_ALT); // robot.keyPress(KeyEvent.VK_W); // robot.keyRelease(KeyEvent.VK_ALT); // robot.keyRelease(KeyEvent.VK_W); 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"); // For linux. //Runtime.getRuntime().exec("gedit"); //定義3秒的延遲以便你打開notepad 哈哈 // Robot 開始寫 robot.delay(3000); for (int i = 0; i < 10; i++) {//輸出10句下面的字母 操做鍵盤鍵 pressKeyWithShift(robot, KeyEvent.VK_H); pressKey(robot, KeyEvent.VK_I); pressKey(robot, KeyEvent.VK_SPACE); //pressKeyWithShift(robot, KeyEvent.VK_H); pressKeyWithShift(robot, KeyEvent.VK_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); // VK_ENTER pressKey(robot, KeyEvent.VK_ENTER); //pressKey(robot, KeyEvent.); } closeApplication(robot); //robot.keyPress(KeyEvent.VK_SPACE); } catch (AWTException e) { e.printStackTrace(); } } }