开发者

Null Pointer Exception in getGraphics() for BufferedImage?

开发者_Go百科public void saveImage(String path){
    BufferedImage image = (BufferedImage) createImage(500, 500);
    Graphics gImage = image.getGraphics(); //<<<<<<<<--- exception
    paint(gImage);
    image = image.getSubimage(0,0,500,500);     
    try {
        ImageIO.write(image, "png", new File(path+".png"));
    }
    catch (Exception e){}
}

Where is the problem ??


Apparently the method createImage(int, int) is returning null. The reason is explained in the documentation:

Returns:
an off-screen drawable image, which can be used for double buffering. The return value may be null if the component is not displayable. This will always happen if GraphicsEnvironment.isHeadless() returns true.


Your NPE is probably not coming from getGraphics but from trying to dereference a null image variable. If your component is not displayable, createImage returns null.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜