简体   繁体   English

Java中VirtualKey代码的怪异行为

[英]Weird behavior of VirtualKey codes in java

I am getting keyboard input from a phone, and trying to display that on the computer using the robot class. 我从电话获取键盘输入,并尝试使用机械手类在计算机上显示该输入。 Since I get ascii from the phone, I have a hashmap for ascii to VirtualKey value conversions. 由于我是从手机上获得ascii的,因此我有了一个hashmap,可以将ascii转换为VirtualKey值。 But my current code has some weird behavior. 但是我当前的代码有一些奇怪的行为。 When I try to map certain symbols in the hashmap such as ! 当我尝试在哈希图中映射某些符号时! " ' @ I get a NullPointer Reference exception when I run it. For excample, for the ! , The phone sends the right unicode value (33) and in the hashtable I have (int)'!' “'@我在运行它时收到一个NullPointer参考异常。例如,对于!,电话发送正确的unicode值(33),并且在哈希表中我具有(int)'!'” as the key, which is also 33. So it should return VK_EXCLAMATION which is what it is mapped to, but it returns null :( Can someone please help? 作为键,也为33。因此它应返回映射到的VK_EXCLAMATION,但它返回null :(有人可以帮忙吗?

Here is my code snipped where I do the lookup: 这是我在其中进行查找的代码片段:

int unicodekey = scanner.nextInt(); //unicode
    robotkey = ascii2VK.asciiForVirtualKey.get(unicodekey);
    robot.keyPress(robotkey);
    robot.keyRelease(robotkey);

And my hashmap looks like this: 我的哈希图看起来像这样:

public class ascii2VK {
      protected static final Map<Integer, Integer> asciiForVirtualKey;
            static {
                asciiForVirtualKey = new HashMap<Integer, Integer>();
                asciiForVirtualKey.put(KeyEvent.VK_UNDEFINED, 0);
                asciiForVirtualKey.put(KeyEvent.VK_QUOTE, (int)'\'');
                asciiForVirtualKey.put(KeyEvent.VK_QUOTEDBL,(int)'"');
                asciiForVirtualKey.put(KeyEvent.VK_AMPERSAND, (int)'&');
                asciiForVirtualKey.put(KeyEvent.VK_BACK_QUOTE, (int)'`');
                asciiForVirtualKey.put(KeyEvent.VK_NUMBER_SIGN, (int)'#');
                asciiForVirtualKey.put(KeyEvent.VK_EXCLAMATION_MARK, (int)'!');
                asciiForVirtualKey.put(KeyEvent.VK_AT, (int)'@');
                asciiForVirtualKey.put(KeyEvent.VK_DOLLAR, (int)'$');
                asciiForVirtualKey.put(KeyEvent.VK_BACK_SLASH, (int)'\\');
                asciiForVirtualKey.put(KeyEvent.VK_SLASH, (int)'/');
    .
    .
    .
    .
    }

You should to reverse keys and values in your map. 您应该反转地图中的键和值。

The KeyEvent.VK_EXCLAMATION_MARK is the constant with value 0x0205 (517 decimal). KeyEvent.VK_EXCLAMATION_MARK是值为0x0205(517十进制)的常数。 But you try to find it by the 33 code, which is actually (int)'!' 但是您尝试通过33代码找到它,实际上是(int)'!'

This will be the right ordering: 这将是正确的顺序:

asciiForVirtualKey.put((int)'!', KeyEvent.VK_EXCLAMATION_MARK);

and so on. 等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM