【问题标题】:Java: Convert string to KeyEvent virtual key code?Java:将字符串转换为 KeyEvent 虚拟键代码?
【发布时间】:2012-10-16 15:55:59
【问题描述】:

我正在尝试编写一个方法,该方法将采用单个字符串并(如果可能)返回它对应的 virtual key code

例如:

private static int getKeyCode(final String key) {
    if(key.length != 1)
        throw new IllegalArgumentException("Only support single characters");

    // Also check to see if the 'key' is (1-9)(A-Z), otherwise exception

    // How to perform the conversion?
}

// Returns KeyEvent.VK_D
MyKeyUtils.getKeyCode("D");

因此,传递 MyKeyUtils.getKeyCode("blah") 会引发 IllegalArgumentException,因为“blah”有 4 个字符。此外,传递 MyKeyUtils.getKeyCode("@") 会引发相同的异常,因为“@”既不是数字 0-9 也不是字符 A - Z。

任何想法如何进行正则表达式检查以及实际转换?提前致谢!

【问题讨论】:

    标签: java regex keyevent keycode


    【解决方案1】:
    if (key.matches("[^1-9A-Z]"))
      throw new IllegalArgumentException("...");
    

    Convertion 可以使用(int) key.charAt(0) 值完成,因为:

    public static final int VK_0 48 
    public static final int VK_1 49 
    ...
    public static final int VK_9 57 
    public static final int VK_A 65 
    ...
    

    【讨论】:

    • 感谢@Omega (+1) - 请在 Prince 的回答下查看我的评论 - 我有同样的问题要问你!
    • 再次感谢@Omega - 所以字符串无法转换为ints,所以你是说我应该使用:Integer.parse(key),这样可以吗?
    • 在转换为int之前,您需要使用key.charAt()
    • @pnongrata - (int) key.charAt(0)
    【解决方案2】:

    将您的输入与^[0-9A-Za-z]$^[\\w&&[^_]]$ 匹配

    if(!key.matches("[0-9A-Za-z]")) 
      throw new IllegalArgumentException("invalid input ...");
    

    int code = key.charAt(0);
    

    【讨论】:

    • 感谢@Prince John Wesley (+1) - 关键代码转换怎么样?有什么想法吗?再次感谢!
    • @pnongrata:我不懂关键码转换。键码只是一个命名变量,保存键的 ascii 值
    猜你喜欢
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 2010-09-24
    相关资源
    最近更新 更多