Monday, June 23, 2008

Automating user input for GUI programs in Java - How?

How can you automate user input for GUI programs in Java?

How to automate GUI programs in Java? Or, How to automate User Inputs from KeyBoard/Mouse for an AWT or Swing based GUI application?

Suppose we want to create a small GUI based demo application which requires automated user input events (which we would have provided by using Keyboard/Mouse). JDK 1.3 introduced a new class named java.awt.Robot, which can be used to automate user input events. We can programmatically create equivalent of user input events by using this class.

This Robot class is primarily used for automated testing of Java platform implementations. This class ctually generates native system instructions for the user events and the execution of these instructions give the end users the same look and feel (and affect as well) what they get by using Keyboard/Mouse for the corresponding actions. For example: the method 'void mouseMove(int x, int y)' of the Robot class when called will not only generate the corresponding mouse move user input event, but it will also move the mouse cursor to the specified co-ordinates.

As we have just discussed that the method calls of this Root class actually results into the corresponding set of native system instructions and hence the platforms which don't allow such low-level input control with the current configuraions and privileges then we'll get an AWTException while trying to instantiate Robot objects.

Example: sample code snippet to use this Robot class


Robot robot = new Robot();

//... storing some key strokes

int keyInput[] ={KeyEvent.VK_A,KeyEvent.VK_B,...KeyEvent.VK_F};

//... a delay of 2 seconds



//... pressing SHIFT for Capital Letter entry



//...pressing one of the input keys from the array



//... releasing any key (say SHIFT) & pressing the ENTER key




We can easily observe that for all possible user input events we can easily build the corresponding set of statements using the methods of this Robot class.


No comments: