Important alert: (current site time 7/15/2013 3:00:59 PM EDT)
 

VB icon

awt.Robot simulates gui user actions

Email
Submitted on: 12/24/2001 12:49:40 PM
By: Paraclete 
Level: Intermediate
User Rating: Unrated
Compatibility: Java (JDK 1.2)
Views: 43898
 
     This program provides an example of using Jdk 1.3's awt.Robot to exercise and validate a GUI. It is a simple, free substitute for Rational's Visual Test tm (which doesn't really work with Java) and Rational-Robot tm.

 
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
 
Terms of Agreement:   
By using this code, you agree to the following terms...   
  1. You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this code from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
				
//**************************************
// Name: awt.Robot simulates gui user actions
// Description:This program provides an example of using Jdk 1.3's awt.Robot to exercise and validate a GUI. It is a simple, free substitute for Rational's Visual Test tm (which doesn't really work with Java) and Rational-Robot tm.
// By: Paraclete
//
// Inputs:Stand-alone application
//
// Assumes:Developed with JBuilder 5.0, but can be compiled from command line:
// javac ChoiceRobot.java
// java ChoiceRobot
//
// You may need to set your Mouse motion speed to the default/medium. This is a known bug in java, at least as of jdk 1.3.0.
//
//This program creates a simple awt panel with an awt.Choice dropdown combo-box with five choices. An awt.Robot is used to simulate mouse moves and clicks to select each choice. Text, button, and label components reflect the Choice selection to verify it is working.
//
//This code is copyrighted and has// limited warranties.Please see http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=2546&lngWId=2//for details.//**************************************

import java.awt.*;
import java.awt.event.*;
/**
 * Class ChoiceRobot
 * Note: May have to set mouse motion to default (medium) for this to work.
 *
 * This program provides an example of using Jdk 1.3's awt.Robot to exercise
 * and validate a GUI. It is a simple, free substitue for Rational's Visual
 * Test tm and Rational-Robot tm.
 *
 * This program creates a simple awt panel with an awt.Choice dropdown combo-box
 * with five choices. An awt.Robot is used to simulate mouse moves and clicks
 * to select each choice. Text, button, and label components reflect the
 * Choice selection to verify it is working.
 *
 * @author Lynn Allan
 * @version 1.00
 * @see awt.Robot
 * javac ChoiceRobot.java
 * java ChoiceRobot
 */
public class ChoiceRobot extends Frame implements ActionListener {
 /** Default private constructor */
 private ChoiceRobot() { }
 /**
* exit from app
* @param event
*/
 public void actionPerformed( ActionEvent event ) { System.exit(0); }
 /** Put TESTING into verField and confirm */
 private final void enterKeystrokes() {
int keyinput[] = {
KeyEvent.VK_T,
KeyEvent.VK_E,
KeyEvent.VK_S,
KeyEvent.VK_T,
KeyEvent.VK_I,
KeyEvent.VK_N,
KeyEvent.VK_G
};
rob.delay(DELAY_SHORT);
rob.keyPress(KeyEvent.VK_SHIFT);
verField.requestFocus();
for (int i = 0; i < keyinput.length; i++) {
 rob.keyPress(keyinput[i]);
 rob.delay(DELAY_SHORT);
}
rob.keyRelease(KeyEvent.VK_SHIFT);
rob.keyPress(KeyEvent.VK_ENTER);
rob.delay(DELAY_LONG);
verify(verField, "TESTINGText:");
 }
 /** invoke testing methods */
 private final void exercise() {
init();
enterKeystrokes();
simulateMouseActions();
System.out.println("errorCount: " + errorCount);
if (errorCount == 0) {
 System.out.println("OK");
}
selectExit();
 }
 /** Prepare panel */
 private final void init() {
panel.add(verButton);
setupExits();
panel.add(verField);
panel.add(lab);
setupChoice();
add(panel);
setSize(SIZE_X, SIZE_Y);
setVisible(true);
try {
 rob = new Robot();
}
catch(AWTException e) { System.out.println("Encountered AWTException"); System.exit(1); }
 }
 /** private inner class for responding to choice events */
 private class ChoiceHandler implements ItemListener {
/**
 * Handle dropdown combobox actions
 * @param event
 */
public void itemStateChanged(ItemEvent event) {
 ItemSelectable item = event.getItemSelectable();
 String itemChoice = item.getSelectedObjects()[0].toString();
 final int score = ch.getSelectedIndex();
 lab.setText("Score: " + score);
 verField.setText(itemChoice);
 verButton.setLabel(itemChoice);
 System.out.println ("State Change: " + itemChoice);
}
 }
 /**
* Use awt.robot to pick a selected index from a choice for a specific interval.
* Note: Uses symbolic constants for offsets in EcrConstants that may differ
* depending on the font used. May have to modify EcrConstants
* @param aChoice
* @param index
* @param interval
*/
 private void selectChoice(Choice aChoice, int index, int interval) {
Point pt = aChoice.getLocationOnScreen();
pt.translate(CHOICE_BASE_OFFSET + CHOICE_BASE_OFFSET,
 CHOICE_BASE_OFFSET + CHOICE_BASE_OFFSET);
rob.mouseMove(pt.x, pt.y);
rob.delay(interval);
rob.mousePress(InputEvent.BUTTON1_MASK);
rob.delay(interval);
rob.mouseRelease(InputEvent.BUTTON1_MASK);
pt.translate(0, (index + 1) * CHOICE_DROP_OFFSET + CHOICE_BASE_OFFSET);
rob.mouseMove(pt.x, pt.y);
rob.delay(interval);
rob.mousePress(InputEvent.BUTTON1_MASK);
rob.delay(interval);
rob.mouseRelease(InputEvent.BUTTON1_MASK);
 }
 /** Use awt.robot to exit from program */
 private void selectExit() {
Point pt = exitButton.getLocationOnScreen();
rob.mouseMove(pt.x + CHOICE_BASE_OFFSET, pt.y + CHOICE_BASE_OFFSET);
rob.mousePress(InputEvent.BUTTON1_MASK);
rob.mouseRelease(InputEvent.BUTTON1_MASK);
 }
 /** Prepare choice drop down combobox */
 private final void setupChoice() {
String [] freq = { "Daily", "Weekly", "Monthly", "Yearly", "Inactive" };
for (int i = 0; i < freq.length; i++) {
ch.add(freq[i]);
}
panel.add(ch);
ch.addItemListener(new ChoiceHandler());
 }
 /** prepare handler for exit button */
 private final void setupExits() {
exitButton.addActionListener(this);
panel.add(exitButton);
addWindowListener(new WindowCloseEventHandler());
 }
 /** Simulate mouse moves & clicks with awt.robot */
 private final void simulateMouseActions() {
verify(verButton, "Verify");
verify(verField, "TESTINGText:");
selectChoice(ch, FREQ_DAILY, DELAY_SHORT);
verify(lab, "Score: 0");
selectChoice(ch, FREQ_YEARLY, DELAY_SHORT);
verify(lab, "Score: 3");
selectChoice(ch, FREQ_MONTHLY, DELAY_SHORT);
selectChoice(ch, FREQ_WEEKLY, DELAY_SHORT);
verify(verField, "Weekly");
selectChoice(ch, FREQ_DAILY, DELAY_SHORT);
selectChoice(ch, FREQ_INACTIVE, DELAY_SHORT);
 }
 /**
* verify that component has expected value
* @param com
* @param verText
*/
 private void verify(Component com, String verText) {
String testText = null;
if (com instanceof Button) {
 testText = ((Button)com).getLabel();
}
else if (com instanceof TextField) {
 testText = ((TextField)com).getText();
}
else if (com instanceof Label) {
 testText = ((Label)com).getText();
}
else {
 System.out.println("Unexpected component type");
 errorCount++;
}
if (verText.equals(testText)) {
 System.out.println("Verified: " + verText);
}
else {
 System.out.println("Invalid: Expected=[" + verText + "] Actual=[" + testText + "]");
 errorCount++;
}
 }
 /** Class WindowCloseEventHandler */
 private class WindowCloseEventHandler extends WindowAdapter {
/**
 * Handle exit event
 * @param event
 */
public void windowClosing(WindowEvent event) {
 System.exit(0);
}
 }
 /**
* main
* @param args[]
*/
 public static void main(String args[]) {
ChoiceRobot test = new ChoiceRobot();
test.exercise();
 }
 /** */ private int errorCount = 0;
 /** */ private Robot rob = null;
 /** */ private final Panel panel = new Panel();
 /** */ private final Button exitButton = new Button("Exit");
 /** */ private final Button verButton = new Button("Verify");
 /** */ private final Choice ch = new Choice();
 /** */ private final Label lab = new Label("Show choice");
 /** */ private final TextField verField = new TextField("Text:");
 /** */ static final int CHOICE_BASE_OFFSET = 5;
 /** */ static final int CHOICE_DROP_OFFSET = 15;
 /** */ static final int DELAY_NONE = 0;
 /** */ static final int DELAY_SHORT = 100;
 /** */ static final int DELAY_LONG = 1000;
 /** */ static final int FREQ_DAILY = 0;
 /** */ static final int FREQ_WEEKLY = 1;
 /** */ static final int FREQ_MONTHLY = 2;
 /** */ static final int FREQ_YEARLY = 3;
 /** */ static final int FREQ_INACTIVE = 4;
 /** */ static final int SIZE_X = 250;
 /** */ static final int SIZE_Y = 100;
}


Other 2 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Intermediate category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments
2/21/2002 12:47:30 PMhui song

The mouse moves irratically in selectChoice(). It does not move to the right locations. The results become even more mild when I put setLocation(623,523) in init().
hui.song@pfizer.com
(If this comment was disrespectful, please report it.)

 
2/26/2002 2:31:37 PMhui song

It seems to behave well now with jdk 1.4.0.
(If this comment was disrespectful, please report it.)

 
3/26/2002 7:12:47 AMCyril

Very usefull code. Thanks
(If this comment was disrespectful, please report it.)

 
5/16/2002 12:40:48 AMjoe

thank you very much!
(If this comment was disrespectful, please report it.)

 
3/6/2005 12:34:53 PM

The mouse moves irratically in
selectChoice(). It does not move to the
right locations. The results become
even more mild when I put
setLocation(623,523) in
init().

(If this comment was disrespectful, please report it.)

 
12/1/2006 8:32:41 AMbilly

it's good
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.