我最近在学习javase,写一个小游戏的时候使用了双缓冲消除闪烁问题的时候遇到了这个问题。if(offScreenImage == null)
    offScreenImage = createImage(GameFrame.SNAKE_WIDTH,GameFrame.SNAKE_HEIGHT);
Graphics2D g2 = (Graphics2D)offScreenImage.getGraphics();
程序运行时,有时候就提示第三行出现了空指针异常,原因就是offScreenImage的值为空。
这个问题不是次次出现,程序启动10次,会有2~3次出现这个异常。之前我也用过这个方法来写其他程序,从来没有出现过这个异常。不知道这次是什么原因。
对了,原来我写的程序是用Frame
这次我用的JFrame和JPanel,这段代码位于JPanel中。不知道是否和这个有关。Java,空指针,JPanel

解决方案 »

  1.   

    createImage这个方法是否能正常获取值呢?最好是Debug一下,或者调试输出一下。
      

  2.   

    if(offScreenImage == null) {
        GraphicsConfiguration gc = ...;
        offScreenImage = gc.createCompatibleImage(GameFrame.SNAKE_WIDTH,GameFrame.SNAKE_HEIGHT);
    }
    Graphics2D g2 = offScreenImage.createGraphics();
      

  3.   

    final BufferedImage compatible = GraphicsEnvironment
    .getLocalGraphicsEnvironment()
    .getDefaultScreenDevice()
    .getDefaultConfiguration()
    .createCompatibleImage(image.getWidth(), image.getHeight(), image.getTransparency());据说性能比较好,没测试过。