Month: April 2012

Automated programs in Java

Introduction

Happy to start blogging after few months. I had to wait to publish my work about 3 months as academic works are getting  heavier day by day. But at the end of the semester I was able to allocate a time slot for my  blogging.

One interesting thing I found in Java was Java Robot class. I said it is interesting because you can create programs which do things automatically. In here you can add key strokes, mouse moves and many things and create an program that work as a robot.

Example commands

keyPress – move to state which you are pressing a key on the keyboard

keyRelease – move to state which you are releasing a key on the keyboard

If you want to press and release a key, you have to use both of these commands.

Without talking further more I’m going to show you how such program can be created.

How to do it

In this example I have created a program which opens the Microsoft Word and paste a screenshot of the current program.

import java.awt.Robot;
import java.awt.event.KeyEvent;

/**
 *
 * @author BUDDHIMA
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        try {
            Robot robot = new Robot();

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

            Thread.sleep(2000);

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

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

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

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

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

            Thread.sleep(7000); // Wait until Word opens

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

            robot.keyPress(KeyEvent.VK_CONTROL);
            robot.keyPress(KeyEvent.VK_V);
            robot.keyRelease(KeyEvent.VK_CONTROL);
            robot.keyRelease(KeyEvent.VK_V);

        } catch (Exception e) {
            System.out.println("Error:"+e.toString());
        }

    }
}

More example codes can be found in references given in References section.

Uses of Robot class

There are certain cases where this Robot class plays an important role. One is creating a game playing clients, self-running demos and where the control of mouse and keyboard is needed.

References

1. Java Doc: http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/Robot.html

2. Baldwin web: http://www.dickbaldwin.com/java/Java1472.htm

3. Automated Game playing video: http://www.youtube.com/watch?v=GK_mjUF6VkM

4. Robot class to play Google doodle guitar: http://www.youtube.com/watch?v=TOvVU56fn24&feature=related