java

位置:IT落伍者 >> java >> 浏览文章

如何在Java中使用Robot类


发布日期:2023年03月13日
 
如何在Java中使用Robot类

JavaawtRobot 类用于控制鼠标和键盘一旦你得到这种控制你能够通过你的Java代码做与鼠标和键盘任何类型的操作这个类通常用于自动化测试先面的代码样例将向您展示Robot类如何处理键盘事件如果你运行此代码并打开notepad您将在notepad中看到HI CAOER赶快试一试吧

import javaawtAWTException;import javaawtRobot;import javaawteventKeyEvent;public class RobotExp {public static void main(String[] args) {try {Robot robot = new Robot();//定义秒的延迟以便你打开notepad 哈哈// Robot 开始写robotdelay();robotkeyPress(KeyEventVK_H);robotkeyPress(KeyEventVK_I);robotkeyPress(KeyEventVK_SPACE);robotkeyPress(KeyEventVK_C);robotkeyPress(KeyEventVK_A);robotkeyPress(KeyEventVK_O);robotkeyPress(KeyEventVK_E);robotkeyPress(KeyEventVK_R);} catch (AWTException e) {eprintStackTrace();}}      }

网友完善了以上代码

import javaawtAWTException;import javaawtRobot;import javaawteventKeyEvent;import javaioIOException;public class RobotExp {public static void pressKey(Robot robot int keyvalue) {robotkeyPress(keyvalue);robotkeyRelease(keyvalue);}public static void pressKeyWithShift(Robot robot int keyvalue) {robotkeyPress(KeyEventVK_SHIFT);robotkeyPress(keyvalue);robotkeyRelease(keyvalue);robotkeyRelease(KeyEventVK_SHIFT);}public static void closeApplication(Robot robot) {// pressKey(robot KeyEventVK_ALT);// pressKey(robot KeyEventVK_F);robotkeyPress(KeyEventVK_ALT);robotkeyPress(KeyEventVK_F);robotkeyRelease(KeyEventVK_ALT);robotkeyRelease(KeyEventVK_F);//for linux// robotkeyPress(KeyEventVK_ALT);// robotkeyPress(KeyEventVK_W);// robotkeyRelease(KeyEventVK_ALT);// robotkeyRelease(KeyEventVK_W);robotkeyPress(KeyEventVK_N);robotkeyRelease(KeyEventVK_N);}public static void main(String[] args) throws IOException {try {Robot robot = new Robot();RuntimegetRuntime()exec(notepad);// For linux//RuntimegetRuntime()exec(gedit);//定义秒的延迟以便你打开notepad 哈哈// Robot 开始写robotdelay();for (int i = ; i < ; i++) {pressKeyWithShift(robot KeyEventVK_H);pressKey(robot KeyEventVK_I);pressKey(robot KeyEventVK_SPACE);//pressKeyWithShift(robot KeyEventVK_H);pressKeyWithShift(robot KeyEventVK_I);pressKey(robot KeyEventVK_SPACE);pressKey(robot KeyEventVK_A);pressKey(robot KeyEventVK_M);pressKey(robot KeyEventVK_SPACE);pressKey(robot KeyEventVK_T);pressKey(robot KeyEventVK_H);pressKey(robot KeyEventVK_E);pressKey(robot KeyEventVK_SPACE);pressKey(robot KeyEventVK_J);pressKey(robot KeyEventVK_A);pressKey(robot KeyEventVK_V);pressKey(robot KeyEventVK_A);pressKey(robot KeyEventVK_SPACE);pressKey(robot KeyEventVK_R);pressKey(robot KeyEventVK_O);pressKey(robot KeyEventVK_B);pressKey(robot KeyEventVK_O);pressKey(robot KeyEventVK_T);// VK_ENTERpressKey(robot KeyEventVK_ENTER);//pressKey(robot KeyEvent);}closeApplication(robot);//robotkeyPress(KeyEventVK_SPACE);} catch (AWTException e) {eprintStackTrace();}}}

               

上一篇:如何解决java的异常处理

下一篇:用Java实现IRC文本到语音转换