java keycode列表,将Char转换为Java KeyEvent KeyCode

本文探讨了一位开发者在编写程序时,如何利用Java AWT Robot类将用户输入的字符串以延迟方式回显到文档中。作者面临的问题是如何高效地将字符转换为对应的关键事件码。文章提出了使用KeyStroke和Character.toUpperCase()等方法来简化按键操作,避免了大规模switch语句,寻求更优雅的解决方案。

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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值