Java下使用Robot模拟键盘按键、鼠标单击、坐标颜色获取

Java下的Robot类可以方便模拟人工键盘按键,鼠标定位并且模拟单击,以及屏幕坐标位置颜色的获取,大家可以扩展思路开发你所需要的功能。

一、键盘模似

import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

public class KeyboardAPI {
    public static void main(String[] args) {
        try {

            Robot robot = new Robot();
            robot.delay(5000);

            while(true) {
                //设置延时
                robot.delay(3000);
                //模拟按键 k
                robot.keyPress(KeyEvent.VK_K);
                //使用随机数0.1-0.5秒
                int KeySecond = (int) (Math.random() * (500 - 100) + 100);
                robot.delay(KeySecond);
                robot.keyRelease(KeyEvent.VK_K);
                System.out.println("当前按键弹出随机数:" + KeySecond);
                //下一轮按键时间,随机数:1-5秒之间
                int LoopDelay = (int) (Math.random() * (5000 - 1000) + 1000);
                System.out.println("下一轮按键随机数:" + LoopDelay);
                robot.delay(LoopDelay);
            }
        } catch (AWTException e) {
            e.printStackTrace();
        }


    }
}

二、鼠标单击

import java.awt.*;
import java.awt.event.InputEvent;

public class Mouse {
    public static void main(String[] args) {

        try {
            Robot robot = new Robot();
            robot.delay(5000);
            //鼠标移动
            robot.mouseMove(1500,500);
            int wait = (int)Math.random()*(500-100)+100;
            //实时模拟人手工延时操作
            robot.delay(wait);
            //鼠标左键单击
            robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            //实时模拟人手工延时操作
            wait = (int)Math.random()*(500-100)+100;
            robot.delay(wait);
            robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }
}

三、屏幕坐标颜色的获取

import java.awt.*;

public class Screen {
    public static void main(String[] args) {
        try {
            Robot robot = new Robot();
            //延时5s
            robot.delay(5000);
            //给出屏幕 x=900,y=500点位置的颜色,可以判断地图位置
            Color pixelColor = robot.getPixelColor(900, 500);
            System.out.println(pixelColor.getRed());
            System.out.println(pixelColor.getBlue());
            System.out.println(pixelColor.getGreen());
        } catch (AWTException e) {
            e.printStackTrace();
        }

    }
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值