Tuesday, November 12, 2013

Robot in Java

Robot is an automation class in AWT package of Java. The Robot class is useful when your Java programs requires test automation, mouse, and keyboard controls. The frequently used methods of the Robot class are shown in the table below.

Method Description
createScreenCapture(Rectangle r) This method returns the image (BufferedImage object) of the captured screen. The dimension of the image is specified by the rectangle r argument.
delay(int mills) The delay method will delay the robot before an event occurs.
getPixelColor(int x,int y) The getPixelColor returns the color at the specified coordinate (x,y) on the screen.
keyPress(int key) This method tells the robot to press a key specified by the key argument. The KeyEvent class defines key constants that can be used in this method.
mouseMove(int x,int y) The mouseMove method will move the mouse pointer to the coordinate (x,y) on the screen.
mousePress(int buttons) This method tells the robot to press the mouse button. The value of buttons argument can be found in the InputEvent class.

In the example code below, the robot is commanded to move to the start button on the Task Bar of Window 7 and the mouse is clicked there. Then the word notepad are typed in the search box and the Enter key is pressed to open the NotePad application.

public class RobotDemo {
public static void main(String[] args){
try {
Robot r=new Robot();
//move to the start button on the Task Bar
r.mouseMove(20, (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight());
r.mousePress(InputEvent.BUTTON1_MASK); //press the left button
//type notepad in the search box
//delay the key pressed
//press enter key

} catch (AWTException e) {
// TODO Auto-generated catch block



Another example is an easy screen capture program. To capture any part of the screen, you will drag the transparent capturing rectangle to a location on the screen where you want to capture. Then press the Enter key to capture the screen. In default, the captured area is 400 pixels wide (width) and 300 pixels long (height). If you wan to increase the dimension of the area to be captured, you will press the ] symbol key. Similarly, to decrease the dimension, simply press the [ symbol key. To minimize the transparent capturing rectangle, press the minus (-) key. When your work completes, you can press the ESC key to exit the program.
The images of the captured screen are saved in the current working directory of the program.

Robot screen capture

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;

class InUI extends JFrame{
int wWin;
int hWin;
int xWin;
int yWin;

Point loc=MouseInfo.getPointerInfo().getLocation();
addKeyListener(new KeyDetector());
addMouseMotionListener(new MouseMove());
Container cont=getContentPane();
cont.setLayout(new BorderLayout());
JLabel lbl=new JLabel("<html>Click and drag this capture area.<br>Press Enter to capture the screen.</html>");
cont.add(lbl, BorderLayout.CENTER);


class KeyDetector extends KeyAdapter{
public void keyPressed(KeyEvent e){
int code=e.getKeyCode();
if(code==27) //exit the program when the Esc key is pressed. 
else if(code==45) //minimize the capture
else if(code==91) //decrease capture area
else if(code==93) //increase capture area
else if(code==10){ //capture the screen when Enter key is pressed
//else if((code==KeyEvent.VK_X) && (e.getModifiers() & KeyEvent.ALT_MASK)!=0 )

class MouseMove extends MouseMotionAdapter{
public void mouseDragged(MouseEvent e){
//change location of the capture area when mouse is dragged
public void increaseSize(){
Dimension ds=Toolkit.getDefaultToolkit().getScreenSize();

public void decreaseSize(){
public void setWinLocation(int x,int y){
this.setLocation(new Point(xWin,yWin));
public void minimize(){
public void capture(){
try {
Robot rb=new Robot();
//capture the target part of the screen
BufferedImage bi=rb.createScreenCapture(new Rectangle(xWin,yWin,wWin,hWin));
//save the image
ImageIO.write(bi, "png", new File(System.getProperty("user.dir")+File.separator+"image"+System.currentTimeMillis()+".png"));
} catch (Exception e) {
// TODO Auto-generated catch block


public class RobotDemo {
public static void main(String[] args){
new InUI();
compass app flashLight app


  1. This blog awesome and i learn a lot about programming from here.The best thing about this blog is that you doing from beginning to experts level.

    Love from Pprogramming

    1. Great Article android based projects

      Java Training in Chennai

      Project Center in Chennai

      Java Training in Chennai

      projects for cse

      The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

  2. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    Java Training in Chennai

  3. I found useful article in your blog. thank you for sharing nice info
    web programming tutorial

  4. Great post! I didn’t knowral of these resources and I’m going to go check them out now!

  5. Your site has a lot of useful information for myself. I visit regularly. Hope to have more quality items.

  6. What’s Going down i am new to this, I stumbled upon this I have discovered It absolutely useful and it has aided me out loads. I am hoping to give a contribution & aid other users like its helped me. Great job.digital marketing manager

  7. Needed to send you that very small remark to say thanks a lot again on the beautiful methods you've documented on this website. It is so shockingly open-handed of you to make unhampered all a number of us would have made available for an e book to help make some bucks for their own end, most importantly seeing that you might well have done it if you wanted. The suggestions additionally served as the easy way to understand that many people have similar passion just like my own to figure out more concerning this problem. I'm certain there are lots of more pleasurable moments up front for many who read carefully your blog. SEO

  8. I loved as much as you will receive carried out right here. The sketch is attractive, your authored material stylish. nonetheless, you command get bought an nervousness over that you want be delivering the following. unwell unquestionably come further formerly again as exactly the same nearly a lot often inside case you shield this increase. Air Charter Service

  9. I'm curious to find out what blog platform you happen to be utilizing? I'm experiencing some minor security issues with my latest website and I would like to find something more risk-free. Do you have any solutions?
    kitchen vinyl flooring singapore

  10. I’ve been exploring for a little bit for any high-quality articles or blog posts in this sort of house . Exploring in Yahoo I eventually stumbled upon this website. Studying this info So i am satisfied to exhibit that I have a very just right uncanny feeling I came upon just what I needed. I such a lot indubitably will make sure to don’t omit this web site and give it a glance regularly.
    commercial renovation

  11. My partner and I stumbled over here by a different page and thought I might check things out. I like what I see so now i am following you. Look forward to exploring your web page yet again.
    office chairs Singapore

  12. I wish to point out my gratitude for your generosity giving support to persons that really need guidance on this particular area. Your special dedication to getting the message all through turned out to be definitely beneficial and has all the time allowed many people much like me to realize their desired goals. Your personal invaluable tips and hints denotes much to me and extremely more to my office colleagues. Regards; from each one of us. advertising agency singapore

  13. Hi, thanks for your blog, if you want to learn about programming languages like java, php, android app, embedded system etc. I think this training institute is the best one.
    Best java training in coimbatore
    Android training in coimbatore
    Networking training in coimbatore

  14. Really informative article.Really looking forward to read more. Really Cool.
    โปรโมชั่นGclub ของทางทีมงานตอนนี้แจกฟรีโบนัส 50%
    เพียงแค่คุณสมัคร สล็อตออนไลน์ กับทางทีมงานของเราเพียงเท่านั้น
    สมัครสล็อตออนไลน์ >>> Goldenslot
    สนใจร่วมสนุกกับ คาสิโนออนไลน์ คลิ๊กได้เลย
    มีทั้งคาสิโนออนไลน์ หวยออนไลน์ ฟุตบอลออนไลน์ สล็อตออนไลน์ และอื่นๆอีกมากมาย

  15. Its like you read my mind! You appear to know so much about this, like you wrote the book in it or something. I think that you could do with a few pics to drive the message home a bit, but other than that, this is wonderful blog. A fantastic read. I'll certainly be back.
    print services singapore

  16. Hello.This article was extremely fascinating, particularly since I was investigating for thoughts on this subject last Tuesday.
    travel insurance singapore

  17. It has been simply incredibly generous with you to provide openly what exactly many individuals wouldíve marketed for an eBook to end up making some cash for their end, primarily given that you could have tried it in the event you wanted.
    Java Training | best java training institute in chennai | java j2ee training in chennai |
    java training chennai | java classes in chennai | java course in chennai | java training with placement in chennai| best java training center in chennai |
    java coaching classes in chennai

  18. Hello there! Do you know if they make any plugins to help with SEO? I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good gains. If you know of any please share. Many thanks!
    hire a professional marketing agency

  19. Thanks for sharing an informative blog keep rocking bring more details.I like the helpful info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite sure I will learn much new stuff right here! Good luck for the next!
    mobile app development training
    mobile application development training online
    web designing course with placement in chennai
    web designing training institute in chennai
    web design and development training
    Web Designing Course Training Institute in Chennai
    mobile app development course
    mobile application development course
    learn mobile application development

  20. Today, I went to the beachfront with my kids. I found a sea shell and gave it to my 4 year old daughter and said "You can hear the ocean if you put this to your ear." She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is completely off topic but I had to tell someone!
    Read reviews about the website designer

  21. I read your article. It is too much appreciable. A very nice information is shared.thanks for your information really good and very nice web design company in velachery

  22. whoah this blog is fantastic i love reading your articles. Keep up the great work! You know, a lot of people are searching around for this information, you could aid them greatly.
    marketing company singapore

  23. Do you have a spam issue on this blog; I also am a blogger, and I was wanting to know your situation; we have developed some nice procedures and we are looking to swap methods with others, please shoot me an e-mail if interested. bhakut Dosha

  24. Bolavita - Situs Taruhan Bola | Live Casino | Sabung Ayam Online | Slot Games |Togel Online Aman Dan Terpercaya

    Minimal Depo & WD Hanya IDR 25.000,- *

    Melayani Deposit Pulsa Telkomsel | XL | Gopay | OVOpay |LinkAja | DANA Serta Semua Bank Indonesia

    Bonus Untuk Member Baru Rp.500.000,-
    Bonus New Member IDR 500.000

    Bonus Cashback Mingguan Hingga 10%
    Bonus Cashback 10%

    Promo Deposit Spesial Happy Friday
    Bonus Flash Deposit Spesial Hari Jumat( Happy Friday)

    Bonus Kemenangan 100% 8x Win Berturut turut
    Bonus 8x Win Sabung Ayam S128 SV388

    Bonus Kemenangan Beruntun Sexy Baccarat
    Bonus 8x Win Sexy Baccarat Casino Online

    Promo Bonus Natal & Tahun Baru Bolivata 2020
    Hadiah Utama Samsung S10

    Kontak :
    • Telegram : https://t.me/bolavita
    • WA Bolavita : https://wa.me/+628122222995/
    • Wechat : Bolavita
    • Line : cs_bolavita

  25. Taldeen is one of the best plastic manufacturing company in Saudi Arabia. They are manufacturing Handling Solutions Plastic products like Plastic Pallets and plastic crates. Here is the link of the product
    Handling Solutions
    Plastic Pallets
    GrueBleen is one of the Branding and Marketing agency Based in Riyadh- Saudi Arabia. The main functions of GrueBleen is Advertising, Branding, Marketing, Office Branding, Exhibition Management and Digital Marketing. Visit the below link to know more about GrueBleen Creative Club.
    Branding Agency Riyadh
    Marketing Agency Riyadh
    Agriculture Solutions – Taldeen is a plastic manufacturing company in Saudi Arabia. They are manufacturing agricultural plastic products like greenhouse cover and hay cover. Visit the below link to know more details
    Agriculture Solutions
    Greenhouse Cover
    GrueBleen – One of the best social media marketing agency in Riyadh- Saudi Arabia. Visit here for the all service details of GrueBleen.
    Social Media Marketing Agency | Social Media Agency In Saudi Arabia | Social Media Agency In Riyadh | Social Media Agency in Jeddah |

  26. Loved to read your blog. I like the significant data you give in your articles. I am impressed the manner in which you introduced your perspectives and appreciating the time and exertion you put into your blog. Much thanks to you such a great amount for sharing this sort of information.
    Visit us for online printing services.

  27. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.

    Security Guard License
    Ontario Security License
    Security License Ontario
    Security License

    Thank you..

  28. Ogen Infosystem is one of the best Website Designing and PPC Company in Delhi, India. Here you will well experience web designers and developers to provide a great website for your business. Our PPC Experts generate leads to your business products at an affordable price.
    Website Designing Company in Delhi

  29. Do you mind on the off chance that I quote a couple of your posts as long as I give credit and sources back to your weblog? My blog webpage is in precisely the same territory of interest as yours and my guests would truly profit by a portion of the data you give here. If it's not too much trouble let me know whether this alright with you. Much obliged to you!

    metal supplier singapore