1

在按钮单击中,我已经实现了代码,当我第一次单击按钮时,它将获取 x,y 位置值,当我第二次单击按钮时,它将获取 x1,y1 值并捕获图像。但不知何故,它还为原始图片添加了黑色背景。我怎样才能避免这种情况?

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;  
}
4

2 回答 2

0

如果这是在mouseClicked(MouseEvent event)方法中(在 a 中MouseListener),您为什么要使用:

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

您可能应该使用以下方法MouseEvent

event.getX();

或者

event.getXOnScreen();

也许这些MouseInfo方法给了你不正确的值。

于 2011-05-25T14:50:26.927 回答
0

我想我找到了问题所在。的构造函数Rectangle采用 ax和 ay起始位置,以及 aheight和 a width。看起来你给了它 2 x/y 点。

试试这个:

int height = Math.max(y - y1, y1 - y);
int width = Math.max(x - x1, x1 - x);
Rectangle rect = new Rectangle(x,y,width, height);
于 2011-05-25T15:41:23.040 回答