绘制Rectangle2D数组时出现空指针异常



我一直试图使矩形数组形成一个游戏网格,出于某种原因,当矩形应该被绘制时,我得到几个空指针异常。我不确定这是否与我设置x,y坐标,宽度,高度或其他东西的方式有关。通过我的测试,似乎这与它无关,但我可能错了。

public class NewClass extends Frame {
    Rectangle2D[][] rectangelMatrix = new Rectangle[4][5];
    int width = 25;
    int height = 25;
    int x = 0;
    int y = 0;
    public NewClass() {
        setSize(1000, 1000);
    }
    public void arraysi() {
        for (int i = 0; i < rectangelMatrix.length; i++) {
            y = y + height;
            for (int j = 0; j < rectangelMatrix[i].length; j++) {
                x = x + width;
                rectangelMatrix[i][j] = new Rectangle(x, y, width, height);
            }
        }
    }
    public void paint(Graphics g) {
        System.out.println("hi");
        Graphics2D g2d = (Graphics2D) g;
        for (int i = 0; i < rectangelMatrix.length; i++) {
            for (int j = 0; j < rectangelMatrix[i].length; j++) {
                // EXCEPTION THROWN FROM LINE BELOW
                g2d.draw(rectangelMatrix[i][j]);
            }
        }
    }
    public void coolios() {
        repaint();
    }
}

从主类调用方法如下:

arraysi()
coolios()

编辑:这里是日志-

exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.awt.geom.Path2D$Float.<init>(Path2D.java:215)
at java.awt.geom.Path2D$Float.<init>(Path2D.java:190)
at sun.java2d.windows.GDIRenderer.doShape(GDIRenderer.java:204)
at sun.java2d.windows.GDIRenderer.draw(GDIRenderer.java:236)
at sun.java2d.pipe.ValidatePipe.draw(ValidatePipe.java:136)
at sun.java2d.SunGraphics2D.draw(SunGraphics2D.java:2336)
at NewClass.paint(NewClass.java:64)
at sun.awt.RepaintArea.paintComponent(RepaintArea.java:248)
at sun.awt.RepaintArea.paint(RepaintArea.java:224)
at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:310)
at sun.awt.windows.WWindowPeer.handleEvent(WWindowPeer.java:695)
at java.awt.Component.dispatchEventImpl(Component.java:4706)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

我觉得你应该打电话给

super.paint(g);

我像下面这样测试你的框架类,它工作没有例外:

public static void main(String[] args) {
        NewClass frame = new NewClass();
        frame.setVisible(true);
        frame.arraysi();
        frame.coolios();
}

我建议您使用Swing JFrame代替,但不要使用SWT Frame。您最好将矩形绘图放在面板中,然后将面板添加到框架中。

我不确定,但尝试使i和j都从1开始?可以工作。

相关内容

  • 没有找到相关文章

最新更新