Search code examples
javaawtrobot

How can I get rid of the black background on images captured with Robot?


In Button click I have implemented the code, when I click the button first time it will get the x, y postion value, when I click the button the second time it will get the x1,y1 value and capture the image. But somehow it is additionally adding a black background to the original picture. How can I avoid this?

Toolkit tool = Toolkit.getDefaultToolkit();
c++;
Dimension d = tool.getScreenSize();
if(c==1)
{
    x = MouseInfo.getPointerInfo().getLocation().x; 
    y = MouseInfo.getPointerInfo().getLocation().y;
}
if(c==2)
{
    int x1= MouseInfo.getPointerInfo().getLocation().x; 
    int y1= MouseInfo.getPointerInfo().getLocation().y;
    Rectangle rect = new Rectangle(x,y,x1,y1);
    Robot robot = new Robot();
    String J="Screen";
    J=J+""+i;
    //*************
    String ext = ".jpg";
    String path = loc+J+ ext;
    File f = new File(path);
    i++;
    Thread t1 = new Thread();
    t1.sleep(100);
    BufferedImage img = robot.createScreenCapture(rect);
    // img.createGraphics();
    ImageIO.write(img,"jpeg",f);
    tool.beep();
    c=0;
    x=0;
    y=0;
    x1=0;
    y1=0;  
}

Solution

  • If this is in a mouseClicked(MouseEvent event) method (in a MouseListener), why are you using:

    MouseInfo.getPointerInfo().getLocation().x;
    

    You should probably be using the methods on MouseEvent:

    event.getX();
    

    or

    event.getXOnScreen();
    

    Perhaps the MouseInfo methods are giving you incorrect values.