机器人类java,输入字符串问题 [英] Robot class java , typing a string issue
问题描述
我正在使用以下循环,但是它仅将第一个字符和其余字符键入数字,知道吗?
I m using the following loop , but its only typing the first charecter and the rest as numbers, any idea ?
import java.awt.*;
import javax.swing.KeyStroke;
public class test {
public static void main(String[] args) throws AWTException
{
Robot r = new Robot();
String s = "Face";
for (int i = 0; i < s.length(); i++)
{
char res = s.charAt(i);
r.keyPress(res);
r.keyRelease(res);
r.delay(1000);
}
}
}
输出类型:F135
OUTPUT typing : F135
推荐答案
keyPress/Release方法需要一个int值,该值表示要键入的字符.这些值是由KeyEvent.VK _ ???确定的每个字符的键控代码.变量.
The keyPress/Release methods need an int value that represents the character you want to type. These value are the key code for each character as determined by the KeyEvent.VK_??? variables.
尝试:
import java.awt.*;
import java.util.*;
import java.lang.reflect.Field;
import java.awt.event.*;
import javax.swing.*;
public class RobotCharacter
{
public static void main(String[] args)
throws Exception
{
JTextField textField = new JTextField(10);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( textField );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
Robot robot = new Robot();
typeCharacter(robot, "a");
typeCharacter(robot, "b");
typeCharacter(robot, "C");
typeCharacter(robot, "D");
}
public static void typeCharacter(Robot robot, String letter)
{
try
{
boolean upperCase = Character.isUpperCase( letter.charAt(0) );
String variableName = "VK_" + letter.toUpperCase();
Class clazz = KeyEvent.class;
Field field = clazz.getField( variableName );
int keyCode = field.getInt(null);
robot.delay(1000);
if (upperCase) robot.keyPress( KeyEvent.VK_SHIFT );
robot.keyPress( keyCode );
robot.keyRelease( keyCode );
if (upperCase) robot.keyRelease( KeyEvent.VK_SHIFT );
}
catch(Exception e)
{
System.out.println(e);
}
}
}
但是,即使这样也不适用于所有角色.例如,在我的键盘上,%"高于"5".您不能使用VK_PERCENT.所需的击键是VK_5以及移位.无法知道键盘的实际映射以自动执行此操作.
However, even this won't work for all characters. For example on my keyboard the "%" is above the "5". You can't use VK_PERCENT. The key stroke needed is VK_5 along with a shift. There is no way to know the actual mapping of your keyboard to do this automatically.
因此,机器人不是实现此目的的好方法.
So a Robot is not a good way to do this.
这篇关于机器人类java,输入字符串问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!