简体   繁体   中英

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. 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)'!' 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?

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). But you try to find it by the 33 code, which is actually (int)'!'

This will be the right ordering:

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

and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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