Robot class java , typing a string issue

WM. picture WM. · Jan 16, 2012 · Viewed 8.7k times · Source

I m using the following loop , but its only typing the first charecter and the rest as numbers, any idea ?

import java.awt.*;

import javax.swing.KeyStroke;

public class test {

    public static void main(String[] args) throws AWTException
    {
        Robot r = new Robot();

        String s = "Face";

        for (int i = 0; i < s.length(); i++) 
        {
            char res = s.charAt(i);
            r.keyPress(res);
            r.keyRelease(res);  
            r.delay(1000);
        }           
    }
}

OUTPUT typing : F135

Answer

camickr picture camickr · Jan 16, 2012

The keyPress/Release methods need an int value that represents the character you want to type. These value are the key code for each character as determined by the KeyEvent.VK_??? variables.

Try:

import java.awt.*;
import java.util.*;
import java.lang.reflect.Field;
import java.awt.event.*;
import javax.swing.*;

public class RobotCharacter
{
    public static void main(String[] args)
        throws Exception
    {
        JTextField textField = new JTextField(10);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.add( textField );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );

        Robot robot = new Robot();
        typeCharacter(robot, "a");
        typeCharacter(robot, "b");
        typeCharacter(robot, "C");
        typeCharacter(robot, "D");
     }

    public static void typeCharacter(Robot robot, String letter)
    {
        try
        {
            boolean upperCase = Character.isUpperCase( letter.charAt(0) );
            String variableName = "VK_" + letter.toUpperCase();

            Class clazz = KeyEvent.class;
            Field field = clazz.getField( variableName );
            int keyCode = field.getInt(null);

            robot.delay(1000);

            if (upperCase) robot.keyPress( KeyEvent.VK_SHIFT );

            robot.keyPress( keyCode );
            robot.keyRelease( keyCode );

            if (upperCase) robot.keyRelease( KeyEvent.VK_SHIFT );
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

However, even this won't work for all characters. For example on my keyboard the "%" is above the "5". You can't use VK_PERCENT. The key stroke needed is VK_5 along with a shift. There is no way to know the actual mapping of your keyboard to do this automatically.

So a Robot is not a good way to do this.