-3
我正在制作游戏并且应绘制矩形,因此我创建了绘制矩形的方法。但我不想只有一个矩形,但很多。所以在for循环中,我尝试调用我创建的paint方法。这就是它给出NullPointerException
的地方。尝试调用paint方法时出现NullPointerException
方法:
public void paint(Graphics g, int i) {
super.paint(g);
g.drawRect(i * 30, 0, 30, 30);
}
for-loop:
for(int i = 0; i < (ScreenSize.screenwidth); i++) {
paint(null, i);
}
全班同学:
public class World extends JPanel {
public void World() {
// Venster
JFrame World = new JFrame("World");
World.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
World.setUndecorated(true);
World.setLayout(null);
// Objecten aanmaken
JPanel panel = new JPanel();
// Objecten toevoegen
World.add(panel);
// Teken vierkantjes
for(int i = 0; i < (ScreenSize.screenwidth); i++) {
paint(null, i);
}
World.setVisible(true);
// Fullscreen, moet als laatste!
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(World);
}
// Functie om vierkantjes te tekenen
public void paint(Graphics g, int i) {
super.paint(g);
g.drawRect(i * 30, 0, 30, 30);
}
}
可能重复[什么是NullPointerException,以及如何解决它?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-doi-i-fix -it) – Frakcool
我永远无法理解为什么人们会连接到该帖子。它绝不会帮助解决绘制“许多矩形”的问题。 NPE是由于设计不佳和缺乏对Swing绘画的理解所致。即使NPE解决了,OP也需要发布另一个关于绘制多个矩形的问题。为什么不花时间看看真正的问题,而不是只看单词“NullPointerException”? – camickr