概述
Java中Robot类位于java.awt.Robot,该类用于为测试自动化,自运行演示程序和其他需要控制鼠标和键盘的应用程序,生成本机系统输入事件.
Robot可以模拟鼠标和键盘的输入,相当于Java版的按键精灵。
1.创建实例
1
| Robot robot = new Robot();
|
延时函数
操作鼠标
鼠标移动
1 2
| robot.mouseMove(int x,int y);
|
鼠标按下
1 2 3 4
| robot.mousePress(鼠标上的按键);
|
鼠标释放
1 2 3 4
| robot.mouseRelease(鼠标上的按键);
|
鼠标滚轮滑动
1 2
| robot.mouseWheel(int wheelAmt);
|
操作键盘
键盘按下指定的键
1 2 3 4 5
|
robot.keyPress(int keycode);
|
键盘释放指定的键
1 2 3 4 5 6
|
robot.keyRelease(int keycode);
|
获取屏幕信息
获取屏幕指定坐标处像素颜色
1 2
| Color color=robot.getPixelColor(int x,int y);
|
截取指定区域的图像(截图功能)
1 2
| BufferedImage bufferedimage=robot.createScreenCapture(Rectangle screenRect);
|
控制类方法
1 2 3 4 5 6 7 8 9 10 11
| robot.delay(int ms);
robot.waitForIdle();
robot.setAutoWaitForIdle(boolean isOn);
robot.setAutoDelay(int ms);
|
示例
示例:截取指定矩形区域的图像,并保存到指定的路径
1 2 3 4 5 6 7 8
| public static void main(String[] args) throws AWTException, IOException { Robot robot=new Robot(); BufferedImage bufferedImage=robot.createScreenCapture(new Rectangle(100,100,500,500)); File f=new File("D:\\save.jpg"); OutputStream os=new FileOutputStream(f); ImageIO.write(bufferedImage, "jpg", os); }
|
示例:在指定区域自动输入指定字符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| robot.mouseMove(342, 626); robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); robot.delay(500); robot.keyPress(KeyEvent.VK_L); robot.keyRelease(KeyEvent.VK_L); robot.delay(500); robot.keyPress(KeyEvent.VK_O); robot.keyRelease(KeyEvent.VK_O); robot.delay(500); robot.keyPress(KeyEvent.VK_V); robot.keyRelease(KeyEvent.VK_V); robot.delay(500); robot.keyPress(KeyEvent.VK_E); robot.keyRelease(KeyEvent.VK_E); robot.delay(500);
|
总结