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();
	}
}
原文地址:https://www.cnblogs.com/llf7/p/13177899.html