-3

I am making a game and it should draw rectangles, so I created a method that draws rectangles. But I don't want just one rectangle, but many. So in a for-loop I try to call the paint method I created. And that is where it gives a NullPointerException.

Method:

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

Whole class:

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

}
Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Frakcool Dec 23 '16 at 21:45
  • 1
    I can never understand why people keep linking to that posting. It in no way will help solve the problem of painting "many rectangles". The NPE is a result of poor design and lack of understanding how painting in Swing works. Even if the NPE is resolved the OP would the need to post another question about painting many rectangles. Why not take the time to look at the real question instead of just looking at the words "NullPointerException"? – camickr Dec 23 '16 at 21:52

1 Answers1

2

And that is where it gives a NullPointerException.

paint(null, i);

Well, of course you get a NPE. You pass null as the parameter to the method.

public void paint(Graphics g, int i) {
    super.paint(g);
    g.drawRect(i * 30, 0, 30, 30);
}

However, even if you fix that problem, that is NOT how you do custom painting. You should NEVER invoke the paint() method directly. Swing will invoke the paint() method when the component needs to be repainted.

But I don't want just one rectangle, but many

So you need to add all your custom painting code to the paintComponent(...) method of the JPanel. Then inside that method you add your for loop. Then you just use the Graphics object passed to the method to do you custom painting.

Read the section from the Swing tutorial on Custom Painting for more information and working examples.

camickr
  • 321,443
  • 19
  • 166
  • 288