I am writing a basic program that asks the user to type in a String, and I am trying to use a Robot (from java.awt.Robot)that will type this message back into another document after a delay. The Problem I have now is that I need to convert whatever I get from message.charAt(i) to a KeyEvent.VK_[insert Char] KeyCode. Is there a better way to do what I am trying to do? I suppose I could always just have a massive switch statement that gets the appropriate KeyCode but I was hoping there would be a more elegant way. My first thought, having done python for awhile, was to make a string "KeyEvent.VK_" + message.charAt(i) and convert that to code somehow, but I think the only way to do that is using Reflection which is discouraged.
解决方案
You could work something out with this:
KeyStroke ks = KeyStroke.getKeyStroke('k', 0);
System.out.println(ks.getKeyCode());
or just use this:
private void writeString(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isUpperCase(c)) {
robot.keyPress(KeyEvent.VK_SHIFT);
}
robot.keyPress(Character.toUpperCase(c));
robot.keyRelease(Character.toUpperCase(c));
if (Character.isUpperCase(c)) {
robot.keyRelease(KeyEvent.VK_SHIFT);
}
}
robot.delay(delay);
}
本文探讨了一位开发者在编写程序时,如何利用Java AWT Robot类将用户输入的字符串以延迟方式回显到文档中。作者面临的问题是如何高效地将字符转换为对应的关键事件码。文章提出了使用KeyStroke和Character.toUpperCase()等方法来简化按键操作,避免了大规模switch语句,寻求更优雅的解决方案。
640

被折叠的 条评论
为什么被折叠?



