Java模拟键盘输入(Robot类模拟键盘输入,解决不准粘贴)

2023-11-01 02:50

本文主要是介绍Java模拟键盘输入(Robot类模拟键盘输入,解决不准粘贴),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.背景

  主要也是为了偷懒,老师不准粘贴。但是提供的测试环境又很不友好,自己敲了一份还要再敲就很烦。于是就写了这个。只能模拟英文和字符输入,中文会直接跳过。点击开始模拟输入会在5秒钟后开始模拟输入。
pic

2.代码

  1. TypeRobot。用Robot来模拟输入的类,挺简单就不多讲了。如果你还需要输入其他字符,参考Java 键盘上各个按键的KeyCode值。
import java.awt.Robot;public class TypeRobot {private Robot robot;private int delay;//传入一个Robot对象public TypeRobot(Robot robot) {this.robot = robot;}//第二个参数是延时TypeRobot(Robot robot, int delay) {this.robot = robot;this.setDelay(delay);}void typeLowerCase(char c) {robot.keyPress(c-32);robot.keyRelease(c-32);delay();}void typeUpperCase(char c) {robot.keyPress(16);robot.keyPress(c);robot.keyRelease(16);robot.keyRelease(c);delay();}void typeNumber(char c) {robot.keyPress(c);robot.keyRelease(c);delay();}void typeOther(char c) {switch(c) {case '+':pressKeyWithCtrl(61);break;case '-':pressKey(45);break;case '*':pressKeyWithCtrl(56);break;case '/':pressKey(47);break;case '\'':pressKey(222);break;case ':':pressKeyWithCtrl(59);break;case '{':pressKeyWithCtrl(91);break;case '}':pressKeyWithCtrl(93);break;case '[':pressKey(91);break;case ']':pressKey(93);break;case ';':pressKey(59);break;case '#':pressKeyWithCtrl(51);break;case '!':pressKeyWithCtrl(49);break;case '%':pressKeyWithCtrl(53);break;case '&':pressKeyWithCtrl(55);break;case '=':pressKey(61);break;case ' ':pressKey(32);break;case '	':pressKey(9);break;case '\n':pressKey(10);break;case '<':pressKeyWithCtrl(44);break;case '>':pressKeyWithCtrl(46);break;case '?':pressKeyWithCtrl(47);break;case '.':pressKey(46);break;case '"':pressKeyWithCtrl(222);break;case '(':pressKeyWithCtrl(57);break;case ')':pressKeyWithCtrl(48);break;case '\\':pressKey(92);break;case ',':pressKey(44);break;case '@':pressKeyWithCtrl(50);break;case '|':pressKeyWithCtrl(92);break;case '^':pressKeyWithCtrl(54);break;case '_':pressKeyWithCtrl(45);break;}}public void setDelay(int delay) {this.delay = Math.max(delay, 0);}public int getDelay() {return delay;}private void delay() {robot.delay(delay);}private void pressKeyWithCtrl(int key) {robot.keyPress(16);robot.keyPress(key);robot.keyRelease(key);robot.keyRelease(16);delay();}private void pressKey(int key) {robot.keyPress(key);robot.keyRelease(key);delay();}
}
  1. Window。窗口类。
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;import javax.swing.*;class Window extends JFrame {private static String typeString = null;private static TypeRobot robot = null;private Thread thread = null;private JFileChooser fileChooser = new JFileChooser(".");private boolean isSuspend = false;Window(String title, Dimension size) {super(title);this.setSize(size);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setLocationRelativeTo(null);try {robot = new TypeRobot(new Robot(), 50);} catch (AWTException e) {System.out.println("创建机器人失败");System.exit(0);}JButton btn_clipboard = new JButton("从剪贴板导入");JButton btn_file = new JButton("从文件导入");JButton btn_ok = new JButton("开始模拟输入");JButton btn_stop = new JButton("暂停");JTextField jf_delay = new JTextField(4);JButton btn_setDelay = new JButton("确定");btn_stop.setEnabled(false);Container c = this.getContentPane();c.setLayout(new BorderLayout());JPanel panelNorth = new JPanel();panelNorth.add(btn_file);panelNorth.add(btn_clipboard);c.add(panelNorth, BorderLayout.NORTH);JTextArea textArea = new JTextArea();textArea.setFont(new Font("宋体", Font.BOLD, 20));JScrollPane jsp = new JScrollPane(textArea);jsp.setPreferredSize(new Dimension(100, 100));c.add(jsp, BorderLayout.CENTER);JPanel panelSouth = new JPanel();panelSouth.add(btn_ok);panelSouth.add(btn_stop);panelSouth.add(new JLabel("延迟:"));panelSouth.add(jf_delay);panelSouth.add(btn_setDelay);c.add(panelSouth, BorderLayout.SOUTH);btn_clipboard.addActionListener(event -> {typeString = getSysClipboardText();textArea.setText(typeString);});btn_setDelay.addActionListener(event->{int delay = Integer.parseInt(jf_delay.getText());robot.setDelay(delay);});btn_file.addActionListener(event -> {int result = fileChooser.showOpenDialog(Window.this);if (result == JFileChooser.APPROVE_OPTION) {typeString = getContentFromFile(fileChooser.getSelectedFile());textArea.setText(typeString);}});btn_stop.addActionListener(event -> {if(!isSuspend) {thread.suspend();isSuspend = !isSuspend;btn_stop.setText("继续");} else {new Thread(() -> {btn_stop.setEnabled(false);for (int i = 0; i < 3; i++) {btn_stop.setText((3 - i) + "");try {Thread.sleep(1000);} catch (InterruptedException e) {}}thread.resume();isSuspend = !isSuspend;btn_stop.setEnabled(true);btn_stop.setText("暂停");}).start();}});btn_ok.addActionListener(event -> {typeString = textArea.getText();if (typeString.isEmpty()) {System.out.println("还没有导入任何数据");} else {btn_stop.setEnabled(true);thread = new Thread(() -> {int delay = 5;btn_ok.setEnabled(false);try {for(int i = 0; i < delay; i++) {btn_ok.setText((delay-i)+"");Thread.sleep(1000);}} catch (InterruptedException e) {e.printStackTrace();}btn_ok.setText("正在模拟...");char temp;for (int i = 0; i < typeString.length(); i++) {temp = typeString.charAt(i);if (temp >= 'A' && temp <= 'Z') {robot.typeUpperCase(temp);} else if (temp >= 'a' && temp <= 'z') {robot.typeLowerCase(temp);} else if (temp >= '0' && temp <= '9') {robot.typeNumber(temp);} else {robot.typeOther(temp);}}btn_ok.setText("开始模拟输入");btn_ok.setEnabled(true);btn_stop.setEnabled(false);});thread.start();}});this.setAlwaysOnTop(true);this.setVisible(true);}private String getContentFromFile(File file) {InputStream is = null;StringBuilder sb = null;try {is = new FileInputStream(file);byte[] buffer = new byte[1024];int len;sb = new StringBuilder();while ((len = is.read(buffer)) >= 0) {sb.append(new String(buffer, 0, len));}} catch (FileNotFoundException e) {System.out.println("文件不存在!");} catch (IOException e1) {System.out.println("IO异常");} finally {if (is != null) {try {is.close();} catch (IOException e) {e.printStackTrace();}}}if (sb == null) {return "";} else {return sb.toString();}}//从剪贴板导入数据private String getSysClipboardText() {String ret = "";Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();Transferable clipTf = sysClip.getContents(null);if (clipTf != null) {if (clipTf.isDataFlavorSupported(DataFlavor.stringFlavor)) {try {ret = (String) clipTf.getTransferData(DataFlavor.stringFlavor);} catch (Exception e) {e.printStackTrace();}}}return ret;}
}
  1. Main。启动类。
import java.awt.Dimension;public class Main {public static void main(String[] args) {new Window("TypeRobot", new Dimension(500, 500));}
}

3.其他

  水平有限,写的不怎么好。

这篇关于Java模拟键盘输入(Robot类模拟键盘输入,解决不准粘贴)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/319946

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

C++右移运算符的一个小坑及解决

《C++右移运算符的一个小坑及解决》文章指出右移运算符处理负数时左侧补1导致死循环,与除法行为不同,强调需注意补码机制以正确统计二进制1的个数... 目录我遇到了这么一个www.chinasem.cn函数由此可以看到也很好理解总结我遇到了这么一个函数template<typename T>unsigned

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。