Type a String using java.awt.Robot

2019-04-03 15:20发布

问题:

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 pre-defined String value at once into a textbox?

robot.keyPress(KeyEvent.VK_1);
robot.keyPress(KeyEvent.VK_1);
robot.keyPress(KeyEvent.VK_1);  
// instead, enter String x = "111"

回答1:

Common solution is to use the clipboard:

String text = "Hello World";
StringSelection stringSelection = new StringSelection(text);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);


回答2:

You need to "type" the character, which is a press AND release action...

robot.keyPress(KeyEvent.VK_1);  
robot.keyRelease(KeyEvent.VK_1);  

Now you could just copy and paste it three times, but I'd just put it in a loop



回答3:

Since Java 7 you can also use KeyEvent.getExtendedKeyCodeForChar(c). An example for lower case only could be:

void sendKeys(Robot robot, String keys) {
    for (char c : keys.toCharArray()) {
        int keyCode = KeyEvent.getExtendedKeyCodeForChar(c);
        if (KeyEvent.CHAR_UNDEFINED == keyCode) {
            throw new RuntimeException(
                "Key code not found for character '" + c + "'");
        }
        robot.keyPress(keyCode);
        robot.delay(100);
        robot.keyRelease(keyCode);
        robot.delay(100);
    }
}


回答4:

You can enter value in a string and then you can use that string as explained by Eng.Fouad. But there is no fun in using it, you can give a try to this

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_H);
robot.keyRelease(KeyEvent.VK_H);
robot.keyPress(KeyEvent.VK_E);
robot.keyRelease(KeyEvent.VK_E);
robot.keyPress(KeyEvent.VK_L);
robot.keyRelease(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_L);
robot.keyRelease(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_O);
robot.keyRelease(KeyEvent.VK_O);

and you can also use Thread.sleep so that it can enter data bit slowly.



回答5:

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<Character, Integer> charMap = new HashMap<Character, Integer>();

    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<Key> stringToKeys(String text){
        List<Key> keys = new ArrayList<Key>();
        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



回答6:

    StringSelection path = new StringSelection("path of your document ");

    // create an object to desktop

    Toolkit tol = Toolkit.getDefaultToolkit();

    // get control of mouse cursor

    Clipboard c = tol.getSystemClipboard();

    // copy the path into mouse
    c.setContents(path, null);

    // create a object of robot class

    Robot r = new Robot();

    r.keyPress(KeyEvent.VK_CONTROL);
    r.keyPress(KeyEvent.VK_V);
    r.keyRelease(KeyEvent.VK_CONTROL);
    r.keyRelease(KeyEvent.VK_V);
    r.keyPress(KeyEvent.VK_ENTER);
    r.keyRelease(KeyEvent.VK_ENTER);

}


回答7:

This doesn't type the entire "string" but helps to type whatever you want other than one character at a time.

    Runtime.getRuntime().exec("notepad.exe");//or anywhere you want.
   Thread.sleep(5000);//not required though gives a good feel.
    Robot r=new Robot();      
     String a="Hi My name is Whatever you want to say.";
    char c;
     int d=a.length(),e=0,f=0;

     while(e<=d)
    {
     c=a.charAt(e);
     f=(int) c; //converts character to Unicode. 
      r.keyPress(KeyEvent.getExtendedKeyCodeForChar(f));
     e++;
       Thread.sleep(150);

       }

see it works perfectly and it's awesome! Though it doesn't work for special characters which cannot be traced by unicode like |,!...etc.