我正在尝试通过使用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); }

最佳答案

您的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);
}

关于java - 尝试在 Canvas 上绘制时出现nullpointerexception错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8552729/

10-09 04:10