FileDocCategorySizeDatePackage
Robot.javaAPI DocJava SE 6 API15624Tue Jun 10 00:25:18 BST 2008java.awt

Robot

public class Robot extends Object
This class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations.

Using the class to generate input events differs from posting events to the AWT event queue or AWT components in that the events are generated in the platform's native input queue. For example, Robot.mouseMove will actually move the mouse cursor instead of just generating mouse move events.

Note that some platforms require special privileges or extensions to access low-level input control. If the current platform configuration does not allow input control, an AWTException will be thrown when trying to construct Robot objects. For example, X-Window systems will throw the exception if the XTEST 2.2 standard extension is not supported (or not enabled) by the X server.

Applications that use Robot for purposes other than self-testing should handle these error conditions gracefully.

version
1.29, 03/21/06
author
Robi Khan
since
1.3

Fields Summary
private static final int
MAX_DELAY
private RobotPeer
peer
private boolean
isAutoWaitForIdle
private int
autoDelay
private static final int
LEGAL_BUTTON_MASK
private Point
gdLoc
private DirectColorModel
screenCapCM
Constructors Summary
public Robot()
Constructs a Robot object in the coordinate system of the primary screen.

throws
AWTException if the platform configuration does not allow low-level input control. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true
throws
SecurityException if createRobot permission is not granted
see
java.awt.GraphicsEnvironment#isHeadless
see
SecurityManager#checkPermission
see
AWTPermission

    
                    	                      	                    	     
        
        if (GraphicsEnvironment.isHeadless()) {
            throw new AWTException("headless environment");
        }
        init(GraphicsEnvironment.getLocalGraphicsEnvironment()
            .getDefaultScreenDevice());
    
public Robot(GraphicsDevice screen)
Creates a Robot for the given screen device. Coordinates passed to Robot method calls like mouseMove and createScreenCapture will be interpreted as being in the same coordinate system as the specified screen. Note that depending on the platform configuration, multiple screens may either:
  • share the same coordinate system to form a combined virtual screen
  • use different coordinate systems to act as independent screens
This constructor is meant for the latter case.

If screen devices are reconfigured such that the coordinate system is affected, the behavior of existing Robot objects is undefined.

param
screen A screen GraphicsDevice indicating the coordinate system the Robot will operate in.
throws
AWTException if the platform configuration does not allow low-level input control. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true.
throws
IllegalArgumentException if screen is not a screen GraphicsDevice.
throws
SecurityException if createRobot permission is not granted
see
java.awt.GraphicsEnvironment#isHeadless
see
GraphicsDevice
see
SecurityManager#checkPermission
see
AWTPermission

	checkIsScreenDevice(screen);
        init(screen);
    
Methods Summary
private voidafterEvent()

	autoWaitForIdle();
	autoDelay();
    
private voidautoDelay()

	delay(autoDelay);
    
private voidautoWaitForIdle()

	if (isAutoWaitForIdle) {
	    waitForIdle();
	}
    
private voidcheckButtonsArgument(int buttons)

	if ( (buttons|LEGAL_BUTTON_MASK) != LEGAL_BUTTON_MASK ) {
	    throw new IllegalArgumentException("Invalid combination of button flags");
	}
    
private voidcheckDelayArgument(int ms)

	if (ms < 0 || ms > MAX_DELAY) {
	    throw new IllegalArgumentException("Delay must be to 0 to 60,000ms");
	}
    
private voidcheckIsScreenDevice(java.awt.GraphicsDevice device)

        if (device == null || device.getType() != GraphicsDevice.TYPE_RASTER_SCREEN) {
            throw new IllegalArgumentException("not a valid screen device");
        }
    
private voidcheckKeycodeArgument(int keycode)

	// rather than build a big table or switch statement here, we'll
	// just check that the key isn't VK_UNDEFINED and assume that the
	// peer implementations will throw an exception for other bogus
	// values e.g. -1, 999999
	if (keycode == KeyEvent.VK_UNDEFINED) {
	    throw new IllegalArgumentException("Invalid key code");
	}
    
private voidcheckNotDispatchThread()

	    
	if (EventQueue.isDispatchThread()) {
	    throw new IllegalThreadStateException("Cannot call method from the event dispatcher thread");
	}
    
private voidcheckRobotAllowed()

	SecurityManager security = System.getSecurityManager();
	if (security != null) {
	    security.checkPermission(SecurityConstants.CREATE_ROBOT_PERMISSION);
	}
    
private static voidcheckScreenCaptureAllowed()

	SecurityManager security = System.getSecurityManager();
	if (security != null) {
	    security.checkPermission(
		SecurityConstants.READ_DISPLAY_PIXELS_PERMISSION);
	}
    
private static voidcheckValidRect(java.awt.Rectangle rect)

	if (rect.width <= 0 || rect.height <= 0) {
	    throw new IllegalArgumentException("Rectangle width and height must be > 0");
	}
    
public synchronized java.awt.image.BufferedImagecreateScreenCapture(java.awt.Rectangle screenRect)
Creates an image containing pixels read from the screen. This image does not include the mouse cursor.

param
screenRect Rect to capture in screen coordinates
return
The captured image
throws
IllegalArgumentException if screenRect width and height are not greater than zero
throws
SecurityException if readDisplayPixels permission is not granted
see
SecurityManager#checkPermission
see
AWTPermission

        checkScreenCaptureAllowed();

        // according to the spec, screenRect is relative to robot's GD
        Rectangle translatedRect = new Rectangle(screenRect);
        translatedRect.translate(gdLoc.x, gdLoc.y);
        checkValidRect(translatedRect);

	BufferedImage image;
	DataBufferInt buffer;
	WritableRaster raster;

    if (screenCapCM == null) {
        /*
         * Fix for 4285201 
         * Create a DirectColorModel equivalent to the default RGB ColorModel,
         * except with no Alpha component.
         */

        screenCapCM = new DirectColorModel(24,
                         /* red mask */    0x00FF0000,
                         /* green mask */  0x0000FF00,
                         /* blue mask */   0x000000FF);
    }

	int pixels[];
    int[] bandmasks = new int[3];

	pixels = peer.getRGBPixels(translatedRect);
	buffer = new DataBufferInt(pixels, pixels.length);

    bandmasks[0] = screenCapCM.getRedMask();
    bandmasks[1] = screenCapCM.getGreenMask();
    bandmasks[2] = screenCapCM.getBlueMask();

    raster = Raster.createPackedRaster(buffer, translatedRect.width, translatedRect.height, translatedRect.width, bandmasks, null);

	image = new BufferedImage(screenCapCM, raster, false, null);

	return image;
    
public synchronized voiddelay(int ms)
Sleeps for the specified time. To catch any InterruptedExceptions that occur, Thread.sleep() may be used instead.

param
ms time to sleep in milliseconds
throws
IllegalArgumentException if ms is not between 0 and 60,000 milliseconds inclusive
see
java.lang.Thread#sleep

	checkDelayArgument(ms);
	try {
	    Thread.sleep(ms);
	} catch(InterruptedException ite) {
	    ite.printStackTrace();
	}
    
public synchronized intgetAutoDelay()
Returns the number of milliseconds this Robot sleeps after generating an event.

	return autoDelay;
    
public synchronized java.awt.ColorgetPixelColor(int x, int y)
Returns the color of a pixel at the given screen coordinates.

param
x X position of pixel
param
y Y position of pixel
return
Color of the pixel

        Color color = new Color(peer.getRGBPixel(gdLoc.x + x, gdLoc.y + y));
        return color;
    
private voidinit(java.awt.GraphicsDevice screen)

        checkRobotAllowed();
        gdLoc = screen.getDefaultConfiguration().getBounds().getLocation();
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        if (toolkit instanceof ComponentFactory) {
            peer = ((ComponentFactory)toolkit).createRobot(this, screen);
        }
    
public synchronized booleanisAutoWaitForIdle()
Returns whether this Robot automatically invokes waitForIdle after generating an event.

return
Whether waitForIdle is automatically called

	return isAutoWaitForIdle;
    
public synchronized voidkeyPress(int keycode)
Presses a given key. The key should be released using the keyRelease method.

Key codes that have more than one physical key associated with them (e.g. KeyEvent.VK_SHIFT could mean either the left or right shift key) will map to the left key.

param
keycode Key to press (e.g. KeyEvent.VK_A)
throws
IllegalArgumentException if keycode is not a valid key
see
#keyRelease(int)
see
java.awt.event.KeyEvent

	checkKeycodeArgument(keycode);
	peer.keyPress(keycode);
	afterEvent();
    
public synchronized voidkeyRelease(int keycode)
Releases a given key.

Key codes that have more than one physical key associated with them (e.g. KeyEvent.VK_SHIFT could mean either the left or right shift key) will map to the left key.

param
keycode Key to release (e.g. KeyEvent.VK_A)
throws
IllegalArgumentException if keycode is not a valid key
see
#keyPress(int)
see
java.awt.event.KeyEvent

	checkKeycodeArgument(keycode);
	peer.keyRelease(keycode);
	afterEvent();
    
public synchronized voidmouseMove(int x, int y)
Moves mouse pointer to given screen coordinates.

param
x X position
param
y Y position

        peer.mouseMove(gdLoc.x + x, gdLoc.y + y);
        afterEvent();
    
public synchronized voidmousePress(int buttons)
Presses one or more mouse buttons. The mouse buttons should be released using the mouseRelease method.

param
buttons the Button mask; a combination of one or more of these flags:
  • InputEvent.BUTTON1_MASK
  • InputEvent.BUTTON2_MASK
  • InputEvent.BUTTON3_MASK
throws
IllegalArgumentException if the button mask is not a valid combination
see
#mouseRelease(int)

	checkButtonsArgument(buttons);
	peer.mousePress(buttons);
	afterEvent();
    
public synchronized voidmouseRelease(int buttons)
Releases one or more mouse buttons.

param
buttons the Button mask; a combination of one or more of these flags:
  • InputEvent.BUTTON1_MASK
  • InputEvent.BUTTON2_MASK
  • InputEvent.BUTTON3_MASK
see
#mousePress(int)
throws
IllegalArgumentException if the button mask is not a valid combination

	checkButtonsArgument(buttons);
	peer.mouseRelease(buttons);
	afterEvent();
    
public synchronized voidmouseWheel(int wheelAmt)
Rotates the scroll wheel on wheel-equipped mice.

param
wheelAmt number of "notches" to move the mouse wheel Negative values indicate movement up/away from the user, positive values indicate movement down/towards the user.
since
1.4

        peer.mouseWheel(wheelAmt);
        afterEvent();
    
public synchronized voidsetAutoDelay(int ms)
Sets the number of milliseconds this Robot sleeps after generating an event.

throws
IllegalArgumentException If ms is not between 0 and 60,000 milliseconds inclusive

	checkDelayArgument(ms);
	autoDelay = ms;
    
public synchronized voidsetAutoWaitForIdle(boolean isOn)
Sets whether this Robot automatically invokes waitForIdle after generating an event.

param
isOn Whether waitForIdle is automatically invoked

	isAutoWaitForIdle = isOn;
    
public synchronized java.lang.StringtoString()
Returns a string representation of this Robot.

return
the string representation.

	String params = "autoDelay = "+getAutoDelay()+", "+"autoWaitForIdle = "+isAutoWaitForIdle();
	return getClass().getName() + "[ " + params + " ]";
    
public synchronized voidwaitForIdle()
Waits until all events currently on the event queue have been processed.

throws
IllegalThreadStateException if called on the AWT event dispatching thread

	checkNotDispatchThread();
	// post a dummy event to the queue so we know when
	// all the events before it have been processed
	try {
            SunToolkit.flushPendingEvents();
	    EventQueue.invokeAndWait( new Runnable() { 
					    public void run() {
						// dummy implementation
					    }
					} );
	} catch(InterruptedException ite) {
	    System.err.println("Robot.waitForIdle, non-fatal exception caught:");
	    ite.printStackTrace();
	} catch(InvocationTargetException ine) {
	    System.err.println("Robot.waitForIdle, non-fatal exception caught:");
	    ine.printStackTrace();
	}