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
r.keyPress(KeyEvent.VK_N);
r.keyPress(KeyEvent.VK_O);
r.keyPress(KeyEvent.VK_T);
r.keyPress(KeyEvent.VK_E);
r.keyPress(KeyEvent.VK_P);
r.keyPress(KeyEvent.VK_A);
r.keyPress(KeyEvent.VK_D);
//delay the key pressed
r.delay(1000);
//press enter key
r.keyPress(KeyEvent.VK_ENTER);

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

}



}


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;
InUI(){

wWin=400;
hWin=300;
setSize(wWin,hWin);
Point loc=MouseInfo.getPointerInfo().getLocation();
xWin=loc.x;
yWin=loc.y;
setLocation(xWin,yWin);
addKeyListener(new KeyDetector());
addMouseMotionListener(new MouseMove());
setUndecorated(true);
setOpacity(0.7f);
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>");
lbl.setHorizontalAlignment(JLabel.CENTER);
cont.add(lbl, BorderLayout.CENTER);
setVisible(true);

}

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

}
}
class MouseMove extends MouseMotionAdapter{
public void mouseDragged(MouseEvent e){
//change location of the capture area when mouse is dragged
setWinLocation(e.getXOnScreen(),e.getYOnScreen());
}
}
public void increaseSize(){
Dimension ds=Toolkit.getDefaultToolkit().getScreenSize();
if(wWin<ds.getWidth()){
wWin+=5;
this.setSize(wWin,hWin);
}
if(hWin<ds.getHeight()){
hWin+=5;
this.setSize(wWin,hWin);
}

}
public void decreaseSize(){
if(wWin>5){
wWin-=5;
this.setSize(wWin,hWin);
}
if(hWin>5){
hWin-=5;
this.setSize(wWin,hWin);
}
}
public void setWinLocation(int x,int y){
xWin=x-wWin/2;
yWin=y-wWin/2;
this.setLocation(new Point(xWin,yWin));
}
public void minimize(){
this.setExtendedState(JFrame.ICONIFIED);
}
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
e.printStackTrace();
}

}
}

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

28 comments:

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

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

    ReplyDelete
  3. 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

    ReplyDelete
  4. 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

    ReplyDelete
  5. 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

    ReplyDelete
  6. 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

    ReplyDelete
  7. 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

    ReplyDelete
  8. 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

    ReplyDelete
  9. 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

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

    ReplyDelete
  11. 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

    ReplyDelete
  12. 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

    ReplyDelete
  13. 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

    ReplyDelete
  14. 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

    ReplyDelete
  15. 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

    ReplyDelete
  16. 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

    ReplyDelete
  17. Thanks For Sharing Your article It is very useful us and amazing blog for the users who want to learn

    Joker Slot
    Slot Pulsa Telkomsel
    Slot Naga777
    Asia777

    ReplyDelete
  18. Very Informative blog thank you for sharing. Keep sharing.

    Best software training institute in Chennai. Make your career development the best by learning software courses.

    android classes in chennai
    blue prism training in chennai
    Docker Training in Chennai

    ReplyDelete
  19. This comment has been removed by the author.

    ReplyDelete
  20. Thank you for sharing information about Java. Keep it up. You can use a monitor with a higher refresh rate to maximize the capabilities of your GPU. There is no purpose in having a potent GPU that can deliver plenty of frames per second without high refresh rates. Typical refresh rates for monitors are 60 Hz, but 144 Hz or greater refresh rates are suggested for gaming. Using any Refresh rate checker tool you can check your monitor refresh rate.

    ReplyDelete
  21. Axure RP Pro Full Version With Crack user is style to the develop, answer, or the experience. Edit the custom groups, pages, & design. User easily Axure RP 8 Full Crack

    ReplyDelete