Robot Class in Java AWT
Robot class in java.awt package itself, means that it acts like a Robot i.e. press and releases a key, press, release, move mouse and can also create screen capture. The following example, illustrates, how to use robot class to open and write in Notepad and again close it.
Robot Class - Open, Write in, Close Notepad.
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
class JavaRobot
{
public static void main(String args[]) throws Exception
{
Robot r=new Robot();
r.setAutoDelay(200);
r.keyPress(KeyEvent.VK_WINDOWS);
r.keyPress(KeyEvent.VK_R);
r.keyRelease(KeyEvent.VK_R);
r.keyRelease(KeyEvent.VK_WINDOWS);
r.keyPress(KeyEvent.VK_N);
r.keyRelease(KeyEvent.VK_N);
r.keyPress(KeyEvent.VK_O);
r.keyRelease(KeyEvent.VK_O);
r.keyPress(KeyEvent.VK_T);
r.keyRelease(KeyEvent.VK_T);
r.keyPress(KeyEvent.VK_E);
r.keyRelease(KeyEvent.VK_E);
r.keyPress(KeyEvent.VK_P);
r.keyRelease(KeyEvent.VK_P);
r.keyPress(KeyEvent.VK_A);
r.keyRelease(KeyEvent.VK_A);
r.keyPress(KeyEvent.VK_D);
r.keyRelease(KeyEvent.VK_D);
r.keyPress(KeyEvent.VK_ENTER);
r.keyPress(KeyEvent.VK_H);
r.keyRelease(KeyEvent.VK_H);
r.keyPress(KeyEvent.VK_A);
r.keyRelease(KeyEvent.VK_A);
r.keyPress(KeyEvent.VK_I);
r.keyRelease(KeyEvent.VK_I);
r.keyPress(KeyEvent.VK_SPACE);
r.keyRelease(KeyEvent.VK_SPACE);
r.keyPress(KeyEvent.VK_B);
r.keyRelease(KeyEvent.VK_B);
r.keyPress(KeyEvent.VK_A);
r.keyRelease(KeyEvent.VK_A);
r.keyPress(KeyEvent.VK_I);
r.keyRelease(KeyEvent.VK_I);
r.keyPress(KeyEvent.VK_ALT);
r.keyPress(KeyEvent.VK_F4);
r.keyRelease(KeyEvent.VK_F4);
r.keyRelease(KeyEvent.VK_ALT);
r.keyPress(KeyEvent.VK_RIGHT);
r.keyRelease(KeyEvent.VK_RIGHT);
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
}
}
keyPress(): Presses a given key.
keyRelease(): Releases a given key, usually the key that is pressed will be released. Nothing happens, if you call keyRelease() for a key that is not pressed.
setAutoDelay(): Auto wait for some time for every action that the Robot class do. Beneficial because, relieves burden in calling delay() all the time.
KeyEvent: Class in the java.awt.event package, generated when keyboard related operation is done.