Thursday, October 21, 2010

how to use robot class in java

/*Here is another Robot java code for you,with explanation....
 this program when you run it writes something for you...mean this program will communicate with you!
  Just kidding.
About Robot:
Robot is a class in Java, where it controls mouse, keyboard with the help of its methods.
Lets start with example...*/
 //Program starts here

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class RobotExp {

 public static void main(String[] args){

//code to open a notepad
  try{

 ProcessBuilder proc=new ProcessBuilder("notepad.exe","AM-ROBOT");
  proc.start();
   }
  catch(Exception k){
  System.out.println(k);
  }

//code to write message
 try {
  Robot robot = new Robot();
  robot.delay(5000); 
  robot.keyPress(KeyEvent.VK_SPACE);
  robot.keyPress(KeyEvent.VK_I);  
  robot.keyPress(KeyEvent.VK_A);
  robot.keyPress(KeyEvent.VK_M);
  robot.keyPress(KeyEvent.VK_SPACE);
  robot.keyPress(KeyEvent.VK_R);
  robot.keyPress(KeyEvent.VK_O);
  robot.keyPress(KeyEvent.VK_B);
  robot.keyPress(KeyEvent.VK_O);
  robot.keyPress(KeyEvent.VK_SPACE);
  robot.keyPress(KeyEvent.VK_T);
  robot.keyPress(KeyEvent.VK_A);
  robot.keyPress(KeyEvent.VK_L);
  robot.keyPress(KeyEvent.VK_K);
  robot.keyPress(KeyEvent.VK_SPACE);
  robot.keyPress(KeyEvent.VK_T); 
  robot.keyPress(KeyEvent.VK_O);
  robot.keyPress(KeyEvent.VK_SPACE);
  robot.keyPress(KeyEvent.VK_M);
  robot.keyPress(KeyEvent.VK_E);
  } 
  catch (AWTException e) {
                 e.printStackTrace();
   }
  }
}
//program completed 


Now compile and run the program.See how compile java in Eclipse  


For better result Just click yes when a notepad opens..

Explanation:


 It is very simple all you have to know is Robot class and its methods.
here in    robot.keyPress(KeyEvent.VK_O);
robot is object created in above program,KeyPress() is a method,and keyEvent is parameter.
VK is virtual key and O is character to be displayed.
you can write any message.With SPACE for gap.


NOTE:

      USE ONLY Single character and Capital,Or else you will get compile time error as compiler  will not understand it.

SEE ROBOT MOUSE which moves mouse pointer

Tags----      Packages in Java     ,       Access specifier      ,     Java history

No comments:

Post a Comment