Type a String using java.awt.Robot

前端 未结 7 1857
难免孤独
难免孤独 2020-12-10 00:46

I already know how to use java.awt.Robot to type a single character using keyPress, as seen below. How can I simply enter a whole

7条回答
  •  爱一瞬间的悲伤
    2020-12-10 01:18

    I think I've implemented better soultion, maybe someone found it usefull (the main approach is to read all values from enum KeyCode and than to put it into a HashMap and use it later to find a int key code)

    public class KeysMapper {
    
        private static HashMap charMap = new HashMap();
    
        static {
            for (KeyCode keyCode : KeyCode.values()) {
                if (keyCode.impl_getCode() >= 65 && keyCode.impl_getCode() <= 90){
                    charMap.put(keyCode.getName().toLowerCase().toCharArray()[0], keyCode.impl_getCode());
                }
                else{
                    charMap.put(keyCode.getName().toLowerCase().toCharArray()[0], keyCode.impl_getCode());
                }
            }
        }
        public static Key charToKey(char c){
            if(c>=65 && c<=90){
                return new Key(charMap.get(c), true);
            } else {
                return new Key(charMap.get(c), false);
            }
        }
    
        public static List stringToKeys(String text){
            List keys = new ArrayList();
            for (char c : text.toCharArray()) {
                keys.add(charToKey(c));
            }
            return keys;
        }
    

    I created also a key class to know whether to type an uppercase or lowercase char:

    public class Key {
    
        int keyCode;
        boolean uppercase;
    
    //getters setter constructors}
    

    and finally you can use it like that (for single character) robot.keyPress(charToKey('a').getKeyCode()); If you want to press an uppercase you have to press and release with shift key simultaneously

提交回复
热议问题