将Char转换为Java KeyEvent KeyCode [英] Converting a Char into Java KeyEvent KeyCode

查看:670
本文介绍了将Char转换为Java KeyEvent KeyCode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个基本程序,要求用户键入一个字符串,我正在尝试使用一个Robot(来自 java.awt.Robot )延迟后将此消息输入另一个文档。我现在遇到的问题是我需要将从 message.charAt(i)获得的任何内容转换为 KeyEvent.VK_ [insert Char] KeyCode。有没有更好的方法来做我想做的事情?我想我总是可以有一个庞大的switch语句来获得适当的KeyCode,但我希望有一个更优雅的方式。我第一次想到,已经做了一段时间的python,就是创建一个字符串KeyEvent.VK_+ message.charAt(i)并以某种方式将其转换为代码,但我认为唯一的方法是使用不鼓励的反射。

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.

推荐答案

你可以解决这个问题:

KeyStroke ks = KeyStroke.getKeyStroke('k', 0);
System.out.println(ks.getKeyCode());

或只是使用它:

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

这篇关于将Char转换为Java KeyEvent KeyCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆