java.awt.robot_java.awt下的Robot类,用来生成原生操作系统的鼠标和键盘事件

Robot的设计目的

This class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations.

这个类主要用于为测试自动化、自动运行演示demo和其他需要鼠标键盘的应用程序生成远程的系统输入事件。Robot的主要目的就是为了促进Java平台实现的自动化测试。

上面的意思就是说,如果需要程序完成一些自动化的任务,就使用java.awt.Robot类,它可以模拟鼠标和键盘的输入。

Robot的简单使用

构造方法

使用默认方法生成对象时,会有异常AWTException需要处理

// 在当前(操作系统)屏幕坐标系中构造一个Robot对象

Robot()

// 为给定屏幕设备创建一个Robot

Robot(GraphicsDevice screen)

常用方法

// 键盘(按下/松开)事件,keycode可以填写 KeyEvent.VK_0 等

keyPress(int keycode);

keyRelease(int keycode);

// 鼠标(按下/松开)事件,buttons可以填写 MouseEvent.BUTTON1_MASK 等

mousePress(int buttons);

mouseRelease(int buttons);

// 鼠标移动,瞬移到屏幕指定的(x,y)位置

mouseMove(int x, int y);

配合使用的其他静态方法

鼠标的当前位置

Point point = MouseInfo.getPointerInfo().getLocation();

屏幕尺寸

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

示例

public class MouseOperationImpl implements MouseOperation {

private Robot robot;

// 将有异常的构造方法不能直接定义成成员变量

// private Robot robot = new Robot();

public MouseOperationImpl() {

try {

robot = new Robot();

} catch (AWTException e) {

e.printStackTrace();

}

}

@Override

public void leftClick() throws Exception {

robot.mousePress(MouseEvent.BUTTON1_MASK);

robot.mouseRelease(MouseEvent.BUTTON1_MASK);

}

@Override

public void rightClick() throws Exception {

robot.mousePress(MouseEvent.BUTTON3_MASK);

robot.mouseRelease(MouseEvent.BUTTON3_MASK);

}

/*

由于鼠标移动是,每次瞬移到给定的(x,y)点,

不能在上一次的基础上进行移动。所以自定义了一个方法

此方法根据移动的角度和长度,计算出位移量。

再在原来的坐标基础上进行位移

*/

@Override

public void moveByAngle(double angle, double length) throws Exception {

Point curMousePos = getMousePos();

// 将传入的double类型的角度,转换成弧度

angle = Math.toRadians(angle);

// 计算位移量,注意窗口的计算左上角是(0,0)。x坐标向左增大,y坐标向下增大

/*

------->

|

|

V

*/

double x = curMousePos.getX() + Math.cos(angle) * length;

double y = curMousePos.getY() + (-Math.sin(angle) * length);

// Math.round(double d)方法的作用是四舍五入

int moveX = (int) Math.round(x);

int moveY = (int) Math.round(y);

robot.mouseMove(moveX, moveY);

}

// 得到当前鼠标坐标

private Point getMousePos() throws Exception {

return MouseInfo.getPointerInfo().getLocation();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值