This snippet shows how to move or re-position the mouse on the screen. This involves the use of Robot API avaiable as part of java.awt package. Basically using the robot.mouseMove(x, y) method the mouse pointer can be repositioned anywhere on the screen.
In addition it also show how to move simulate the mouse wheel movement, which creates a window scroll effect in the current window.
Using these techniques Automation can be achieved, by positioning the mouse on a button and invoking the keyPress(.) and keyRelease() method for the Robot as well, simulating a human click.
package com.livrona.snippets.device;
import java.awt.Robot;
/**
* This snippet shows how to mouse move programatically on the screen.
*/
publicclass MouseMovements {
/**
* main(args[]) method
*
* @param args
* @throws Exception
*/
publicstaticvoid main(String[] args) throws Exception {
// create a new instance, automation event generator
Robot robot =new Robot();
// location co-ordinated
int x =0;
int y =0;
int steps =3;
// move the mouse to location
// the mouse would move diagonally across the screen
for (int i =0; i < steps; i++) {
// move mouse to location
robot.mouseMove(x, y);
System.out.println("Mouse at : "+ x +"," + y);
robot.delay(1000); // introduce delay to see the movements
// increment the co-ordinates
x = x +20;
y = y +20;
}
// scroll the wheel
// depending on the activate window, it would scroll up and down
// say 100 units
robot.mouseWheel(100);
robot.mouseWheel(-100);
}
}