尝试绘制到画布时出现nullpointerexception错误

时间:2011-12-18 15:28:17

标签: java

我试图通过使用2D阵列在屏幕上绘制一个棋盘图案,并根据从阵列位置读取的字符在当前坐标处绘制10x10像素块。我认为这是与问题相关的所有代码:

public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        g.fillRect(0, 0, this.getWidth(),this.getHeight());
        for(int x = 0;x<=3;x++){
            for(int y = 0;y<=3;y++){
                                // NPE occurs on this line:
                if (globalmap[x][y] == '1'){g2d.fillRect(10*y, 10*x, 10,10);}
            }
        }
}

这是地图数组:

0000
0011
0100
0000

堆栈追踪:

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at com.side.side.GameEngine.paint(GameEngine.java:64)
        at javax.swing.JComponent.paintChildren(Unknown Source)
        at javax.swing.JComponent.paint(Unknown Source)
        at javax.swing.JComponent.paintChildren(Unknown Source)
        at javax.swing.JComponent.paint(Unknown Source)
        at javax.swing.JLayeredPane.paint(Unknown Source)
        at javax.swing.JComponent.paintChildren(Unknown Source)
        at javax.swing.JComponent.paintToOffscreen(Unknown Source)
        at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
        at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
        at javax.swing.RepaintManager.paint(Unknown Source)
        at javax.swing.JComponent.paint(Unknown Source)
        at java.awt.GraphicsCallback$PaintCallback.run(Unknown Source)
        at sun.awt.SunGraphicsCallback.runOneComponent(Unknown Source)
        at sun.awt.SunGraphicsCallback.runComponents(Unknown Source)
        at java.awt.Container.paint(Unknown Source)
        at java.awt.Window.paint(Unknown Source)
        at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
        at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
        at javax.swing.RepaintManager.seqPaintDirtyRegions(Unknown Source)
        at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
        at java.awt.event.InvocationEvent.dispatch(Unknown Source)
        at java.awt.EventQueue.dispatchEvent(Unknown Source)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
       at java.awt.EventDispatchThread.run(Unknown Source)

第64行:

if (globalmap[x][y] == '1') { g2d.fillRect(10*y, 10*x, 10,10); }

1 个答案:

答案 0 :(得分:1)

可能你的globalmap数组元素为null,但根据你发布的内容很难分辨。请注意,这条线很糟糕:

 if (globalmap[x][y] == '1'){g2d.fillRect(10*y, 10*x, 10,10);}

如果仅用于调试目的,您需要将其分散到多行:

if (globalmap[x][y] == '1') {
    g2d.fillRect(10*y, 10*x, 10,10);
}