clase robot
TRANSCRIPT
Clase Robot
java.awt
java.lang.Object
java.awt.Robot
public class Robotextends 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.
Constructor Summary
Constructors
Constructor and Description
Robot()
Constructs a Robot object in the coordinate system of the primary screen.
Robot(GraphicsDevice screen)
Creates a Robot for the given screen device.
Method Summary
Methods
Modifier and Type Method and Description
BufferedImage createScreenCapture(Rectangle screenRect)
Creates an image containing pixels read from the screen.
void delay(int ms)
Sleeps for the specified time.
int getAutoDelay()
Returns the number of milliseconds this Robot sleeps after generating an event.
Color getPixelColor(int x, int y)
Returns the color of a pixel at the given screen coordinates.
boolean isAutoWaitForIdle()
Returns whether this Robot automatically invokes waitForIdle
void keyPress(int keycode)
Presses a given key.
void keyRelease(int keycode)
Releases a given key.
void mouseMove(int x, int y)
Moves mouse pointer to given screen coordinates.
void mousePress(int buttons)
Presses one or more mouse buttons.
void mouseRelease(int buttons)
Releases one or more mouse buttons.
void mouseWheel(int wheelAmt)
Rotates the scroll wheel on wheel-equipped mice.
void setAutoDelay(int ms)
Sets the number of milliseconds this Robot sleeps after generating an event.
void setAutoWaitForIdle(boolean isOn)
Sets whether this Robot automatically invokes waitForIdle after generating an event.
String toString()
Returns a string representation of this Robot.
void waitForIdle()
Waits until all events currently on the event queue have been processed.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
Constructor Detail
Robot
public Robot()
throws AWTException
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
SecurityException - if createRobot permission is not granted
See Also:
GraphicsEnvironment.isHeadless(), SecurityManager.checkPermission(java.security.Permission), AWTPermission
Robot
public Robot(GraphicsDevice screen)
throws AWTException
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.
Parameters:
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.
IllegalArgumentException - if screen is not a screen GraphicsDevice.
SecurityException - if createRobot permission is not granted
See Also:
GraphicsEnvironment.isHeadless(), GraphicsDevice, SecurityManager.checkPermission(java.security.Permission), AWTPermission
Method Detail
mouseMove
public void mouseMove(int x,
int y)
Moves mouse pointer to given screen coordinates.
Parameters:
x - X position
y - Y position
mousePress
public void mousePress(int buttons)
Presses one or more mouse buttons. The mouse buttons should be released using the mouseRelease(int) method.
Parameters:
buttons - the Button mask; a combination of one or more mouse button masks.
It is allowed to use only a combination of valid values as a buttons parameter. A valid combination consists of InputEvent.BUTTON1_DOWN_MASK, InputEvent.BUTTON2_DOWN_MASK, InputEvent.BUTTON3_DOWN_MASK and values returned by the InputEvent.getMaskForButton(button) method. The valid combination also depends on a Toolkit.areExtraMouseButtonsEnabled() value as follows:
If support for extended mouse buttons is disabled by Java then it is allowed to use only the following standard button masks: InputEvent.BUTTON1_DOWN_MASK, InputEvent.BUTTON2_DOWN_MASK,InputEvent.BUTTON3_DOWN_MASK.
If support for extended mouse buttons is enabled by Java then it is allowed to use the standard button masks and masks for existing extended mouse buttons, if the mouse has more then three buttons. In that way, it is allowed to use the button masks corresponding to the buttons in the range from 1 to MouseInfo.getNumberOfButtons(). It is recommended to use the InputEvent.getMaskForButton(button) method to obtain the mask for any mouse button by its number.
The following standard button masks are also accepted:
InputEvent.BUTTON1_MASK InputEvent.BUTTON2_MASK InputEvent.BUTTON3_MASK
However, it is recommended to use InputEvent.BUTTON1_DOWN_MASK, InputEvent.BUTTON2_DOWN_MASK, InputEvent.BUTTON3_DOWN_MASK instead. Either extended _DOWN_MASK or
old _MASK values should be used, but both those models should not be mixed.
Throws:
IllegalArgumentException - if the buttons mask contains the mask for extra
mouse button and support for extended mouse buttons is disabled by Java
IllegalArgumentException - if the buttons mask contains the mask for extra
mouse button that does not exist on the mouse and support for extended mouse buttons is enabled by Java
See Also:
mouseRelease(int), InputEvent.getMaskForButton(int), Toolkit.areExtraMouseButtonsEnabled(), MouseInfo.getNumberOfButtons(), MouseEvent
mouseRelease
public void mouseRelease(int buttons)
Releases one or more mouse buttons.
Parameters:
buttons - the Button mask; a combination of one or more mouse button masks.
It is allowed to use only a combination of valid values as a buttons parameter. A valid combination consists of InputEvent.BUTTON1_DOWN_MASK, InputEvent.BUTTON2_DOWN_MASK, InputEvent.BUTTON3_DOWN_MASK and values returned by the InputEvent.getMaskForButton(button) method. The valid combination also depends on a Toolkit.areExtraMouseButtonsEnabled() value as follows:
If the support for extended mouse buttons is disabled by Java then it is allowed to use only the following standard button masks: InputEvent.BUTTON1_DOWN_MASK, InputEvent.BUTTON2_DOWN_MASK,InputEvent.BUTTON3_DOWN_MASK.
If the support for extended mouse buttons is enabled by Java then it is allowed to use the standard button masks and masks for existing extended mouse buttons, if the mouse has more then three buttons. In that way, it is allowed to use the button masks corresponding to the buttons in the range from 1 to MouseInfo.getNumberOfButtons(). It is recommended to use the InputEvent.getMaskForButton(button) method to obtain the mask for any mouse button by its number.
The following standard button masks are also accepted:
InputEvent.BUTTON1_MASK InputEvent.BUTTON2_MASK InputEvent.BUTTON3_MASK
However, it is recommended to use InputEvent.BUTTON1_DOWN_MASK, InputEvent.BUTTON2_DOWN_MASK, InputEvent.BUTTON3_DOWN_MASK instead. Either extended _DOWN_MASK or
old _MASK values should be used, but both those models should not be mixed.
Throws:
IllegalArgumentException - if the buttons mask contains the mask for extra
mouse button and support for extended mouse buttons is disabled by Java
IllegalArgumentException - if the buttons mask contains the mask for extra
mouse button that does not exist on the mouse and support for extended mouse buttons is enabled by Java
See Also:
mousePress(int), InputEvent.getMaskForButton(int), Toolkit.areExtraMouseButtonsEnabled(), MouseInfo.getNumberOfButtons(), MouseEvent
mouseWheel
public void mouseWheel(int wheelAmt)
Rotates the scroll wheel on wheel-equipped mice.
Parameters:
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
keyPress
public void keyPress(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.
Parameters:
keycode - Key to press (e.g. KeyEvent.VK_A)
Throws:
IllegalArgumentException - if keycode is not a valid key
See Also:
keyRelease(int), KeyEvent
keyRelease
public void keyRelease(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.
Parameters:
keycode - Key to release (e.g. KeyEvent.VK_A)
Throws:
IllegalArgumentException - if keycode is not a valid key
See Also:
keyPress(int), KeyEvent
getPixelColor
public Color getPixelColor(int x,
int y)
Returns the color of a pixel at the given screen coordinates.
Parameters:
x - X position of pixel
y - Y position of pixel
Returns:
Color of the pixel
createScreenCapture
public BufferedImage createScreenCapture(Rectangle screenRect)
Creates an image containing pixels read from the screen. This image does not include the mouse cursor.
Parameters:
screenRect - Rect to capture in screen coordinates
Returns:
The captured image
Throws:
IllegalArgumentException - if screenRect width and height are not greater than
zero
SecurityException - if readDisplayPixels permission is not granted
See Also:
SecurityManager.checkPermission(java.security.Permission), AWTPermission
isAutoWaitForIdle
public boolean isAutoWaitForIdle()
Returns whether this Robot automatically invokes waitForIdle after generating an event.
Returns:
Whether waitForIdle is automatically called
setAutoWaitForIdle
public void setAutoWaitForIdle(boolean isOn)
Sets whether this Robot automatically invokes waitForIdle after generating an event.
Parameters:
isOn - Whether waitForIdle is automatically invoked
getAutoDelay
public int getAutoDelay()
Returns the number of milliseconds this Robot sleeps after generating an event.
setAutoDelay
public void setAutoDelay(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
delay
public void delay(int ms)
Sleeps for the specified time. To catch any InterruptedExceptions that
occur, Thread.sleep() may be used instead.
Parameters:
ms - time to sleep in milliseconds
Throws:
IllegalArgumentException - if ms is not between 0 and 60,000 milliseconds
inclusive
See Also:
Thread.sleep(long)
waitForIdle
public void waitForIdle()
Waits until all events currently on the event queue have been processed.
Throws:
IllegalThreadStateException - if called on the AWT event dispatching thread
toString
public String toString()
Returns a string representation of this Robot.
Overrides:
toString in class Object
Returns:
the string representation.
===================================================================
Esta clase es muy util, ya que con ella podemos tomar una foto a la pantalla, dar un clic automatico, o sea , sin que tengamos que tocar el mouse, escribir un texto sin siquiera tocar el teclado, capturar el color de un pixel especifico en la pantalla.
createScreenCapture
Robot r=new Robot();
BufferedImage imagen =r.createScreenCapture(Rectangle rec);
Con este metodo podemos capturar la pantalla, el tamaño se indica con un rectangulo que indica la posicion en la pantalla, y el ancho y alto.
getPixelColor
Color c=r.getPixelColor(int x, int y);
Este metodo retorna el color del pixel que esta en la posicion indicada por X y Y.
keyPress
r.keyPress(int keyCode);
Este metodo presiona la tecla que se le indique, keyCode representa el codigo de la tecla por ejemplo para pulsar Enter, el codigo es keyEvent.VK_ENTER.
Si deseas ver todas las constantes de todas las teclas entra aqui.
mousePress
r.mousePress(int boton);
Este metodo da un clic, y dependiendo del atributo puede ser con el boton izquierdo, derecho, centro. Si es con el izquierdo InputEvent.BUTTON1_MASK si es con el boton del centro se usa InputEvent.BUTTON2_MASK y si es con el derecho se usa InputEvent.BUTTON3_MASK .
mouseMove
r.mouseMove(int x, int y);
Este metodo mueve el mouse a la posicion indicada con los atributos X y Y.
Clase Robot
Como hemos comentado anteriormente con la clase Robot podemos presionar las teclas
de nuestro teclado, en este caso vamos a presionar las teclas ” P R O B A N D O ” ,
primero vamos a abrir el notepad de windows utilizando el siguiente
códigoRuntime.getRuntime().exec(“notepad”);. Después vamos a utilizar el
método delay()para dejar un corto espacio de tiempo en el que windows va a abrir el
notepad y posicionará el foco en él, por último nuestro robot presionará las teclas.
El código completo para escribir con la clase robot sería así:
import java.awt.Robot;import java.awt.event.KeyEvent; public class Escribe { public static void main(String[] args) {
try {Robot robot = new Robot();
Runtime.getRuntime().exec("notepad");
robot.delay(100);robot.keyPress(KeyEvent.VK_P);robot.keyPress(KeyEvent.VK_R);robot.keyPress(KeyEvent.VK_O);robot.keyPress(KeyEvent.VK_B);robot.keyPress(KeyEvent.VK_A);robot.keyPress(KeyEvent.VK_N);robot.keyPress(KeyEvent.VK_D);robot.keyPress(KeyEvent.VK_O);
} catch (Exception e) {System.out.println(e);
}}}
La clase Robot en java se encuentra en el paquete java.awt y tiene funcionalidades bastantes interesantes, para los que nos gusta improvisar con los códigos no viene de maravilla ya que sus funcionalidades se prestan para cosas bastante ocurrentes y útiles por su puesto.
1- Haciendo travesuras con el mouse:
Una de sus utilidades es simular la utilización del mouse por un usuario por ejemplo:Robot robot = new Robot();
//Movemos el mouse a la posición de la pantalla que queramos
robot.mouseMove(x, y);
//presionamos el click derechorobot.mousePress(InputEvent.BUTTON2_MASK);robot.mouseRelease(InputEvent.BUTTON2_MASK);
2- El teclado esta loco:
Es posible simular las pulsaciones de teclas de un usuario utilizando alguna de las bondades que nos brinda Robot.
import java.awt.AWTException;import java.awt.Robot;import java.awt.event.KeyEvent;
public class test{/public static void main(String[] args){try{Robot robot = new Robot();// abriendo el menu iniciorobot.keyPress(KeyEvent.VK_WINDOWS);robot.keyRelease(KeyEvent.VK_WINDOWS);// lanzando el exploreradorrobot.keyPress(KeyEvent.VK_WINDOWS);robot.keyPress(KeyEvent.VK_E);robot.keyRelease(KeyEvent.VK_E);robot.keyRelease(KeyEvent.VK_WINDOWS);}catch (AWTException e){e.printStackTrace();}}}
3- Espiando lo que pasa en la PC.
Nuestra mágica clase nos permite realizar capturas de nuestra pantalla con gran nitidez, hay que destacar que cuando realizamos esta función no se refleja el mouse en dicha imagen pero eso se puede resobre.
MouseInfo.getPointerInfo().getLocation().x;MouseInfo.getPointerInfo().getLocation().y;
Resuelto el problema pasaremos al plato fuerte:
import java.awt.AWTException;import java.awt.Rectangle;import java.awt.Robot;import java.awt.Toolkit;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;
public class test{
public static void main(String[] args) throws IOException{try{Robot robot = new Robot();BufferedImage pantalla = robot.createScreenCapture(new Rectangle (Toolkit.getDefaultToolkit().getScreenSize()));File file = new File("C:\\captura.jpg");ImageIO.write(pantalla, "jpg", file);}catch (AWTException e){e.printStackTrace();}}}