我应该明确处置Graphics对象吗?

时间:2015-03-26 08:46:24

标签: java swing awt

javadoc说:

  

为了提高效率,程序员在使用完成后应该调用dispose   图形对象仅在直接从组件创建时才会生成   另一个Graphics对象。

所以在下面的代码中,我应该在返回之前调用graphics.dispose()吗? 或者,我可以吗?

{  ...  
BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB);  

java.awt.Graphics graphics=result.getGraphics();

graphics.drawImage(im.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);  

return result;  
}

返回BufferedImage result并在别处使用。

3 个答案:

答案 0 :(得分:4)

Graphics对象可以处置,应该处理。

getGraphics BufferedImage内部代表createGraphicscreateGraphics,因此没有区别。 GraphicsEnvironment调用最终会委托给相应的SunGraphicsEnvironment实现,其中(new)创建一个{strong> SunGraphics2D 实例{{1} }}。

最后,dispose的{​​{1}}方法说明如下:

SunGraphics2D

还提供对齐为什么 /** * This object has no resources to dispose of per se, but the * doc comments for the base method in java.awt.Graphics imply * that this object will not be useable after it is disposed. * So, we sabotage the object to prevent further use to prevent * developers from relying on behavior that may not work on * other, less forgiving, VMs that really need to dispose of * resources. */ public void dispose() { surfaceData = NullSurfaceData.theInstance; invalidatePipe(); } 确实应该被调用(即使在默认实现中不是绝对必要的)

答案 1 :(得分:1)

public class Main{

    public static void main(String[] args) {
        BufferedImage img = get();

        Graphics g = img.getGraphics();

        //g.drawOval(5, 5, 5, 5); //this statement will work (you'll see the cirle)

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write( img, "jpg", baos );

            baos.flush();
            byte[] imageInByte = baos.toByteArray();
            baos.close();

            Files.write(Paths.get("test2.png"), imageInByte);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public static BufferedImage get(){
        BufferedImage res = new BufferedImage(50, 50, BufferedImage.TYPE_INT_ARGB);

        Graphics g = res.getGraphics();

        g.drawRect(0, 0, 20, 20);

        g.dispose();

        g.drawOval(5, 5, 5, 5); //this statement won't work, you'll only see the rect

        return res;
    }


}

正如您所看到的,您可以在方法中保存(并且应该)graphics

之后您无法在方法中使用图形对象,因此当您运行代码时,图片中不会出现圆圈。但是,如果您在方法中注释掉g.drawOval(5,5,5,5),但在main - 方法的同一语句中发表评论,您会看到一个圆圈。所以你可以在之后使用它。

答案 2 :(得分:0)

由于JavaDoc getGpahics()方法转发到createGraphics(),您应该在方法的末尾处理Graphics对象。