In Button click I have implemented the code, when I c开发者_如何转开发lick 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;
}
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.
I think I found the issue. The constructor for Rectangle
takes an x
and a y
starting position, and a height
and a width
. It looks like you are giving it 2 x/y points.
Try this instead:
int height = Math.max(y - y1, y1 - y);
int width = Math.max(x - x1, x1 - x);
Rectangle rect = new Rectangle(x,y,width, height);
精彩评论