本文主要是介绍Java模拟键盘输入(Robot类模拟键盘输入,解决不准粘贴),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.背景
主要也是为了偷懒,老师不准粘贴。但是提供的测试环境又很不友好,自己敲了一份还要再敲就很烦。于是就写了这个。只能模拟英文和字符输入,中文会直接跳过。点击开始模拟输入会在5秒钟后开始模拟输入。
2.代码
- 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();}
}
- 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;}
}
- Main。启动类。
import java.awt.Dimension;public class Main {public static void main(String[] args) {new Window("TypeRobot", new Dimension(500, 500));}
}
3.其他
水平有限,写的不怎么好。
这篇关于Java模拟键盘输入(Robot类模拟键盘输入,解决不准粘贴)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!