我一直试图制作一个矩形数组来形成一个游戏网格,出于某种原因,当应该绘制矩形时,我会得到几个Nullpointer异常。我不确定这是否与我设置x,y co-ords,宽度,高度或其他完全相同的方式有关。通过我的测试,它似乎与它无关,但我可能是错的。< / p>
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)
答案 0 :(得分:0)
我认为你应该致电
super.paint(g);
来自你的绘画方法。
答案 1 :(得分:0)
我测试你的帧类如下,它无一例外地工作:
public static void main(String[] args) {
NewClass frame = new NewClass();
frame.setVisible(true);
frame.arraysi();
frame.coolios();
}
我建议您使用Swing JFrame,但不要使用SWT Frame。 并且您最好将矩形绘图放在面板中,然后将面板添加到框架中。
答案 2 :(得分:-3)
我不确定但尝试让i和j都从1开始? 可以工作。