0

I'm working on creating a simple Java2D program. It is supposed to draw rectangles from another class but it does not work. I'd really appreciate it if one of you guys could take a few moments to look where I'm going wrong. This is my last assignment due tomorrow.

Here's the code which I have worked on so far:

Block.java

public class Block extends JPanel {

    public Graphics2D g;
    protected int posX = 0;
    protected int posY = 0;
    protected int w = 100;
    protected int h = 100;

    public void draw() {
        g.setColor(Color.GREEN);
        g.fillRect(posX, posY, w, h);
    }
}

Here is the main class:

public class main {

    private static final long serialVersionUID = 1L;

    private Block[] pie = new Block[5];
    Timer timer;

    main() {
        final JPanel screen = new JPanel() {

            int x = 0;
            int step = 10;

            public void paintComponent(Graphics g) {

                super.paintComponent(g);

                pie[0].g = (Graphics2D) g;
                pie[0].draw();

            }

        };

        JFrame f = new JFrame("Test Lab");
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.setContentPane(screen);
        f.pack();
        f.setLocationByPlatform(true);
        f.setResizable(false);
        f.setVisible(true);

    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable(){
            public void run(){
                new main();
            }
        });     
    }

}

Many thanks.

cucumber_boy
  • 173
  • 1
  • 12
dkregen
  • 448
  • 2
  • 6
  • 16
  • 1
    So what's the problem? What is supposed to happen and what's happening instead? – Mike G Nov 04 '15 at 18:28
  • I have no idea. There are several messages appear on the console : Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at main$1.paintComponent(main.java:54) at javax.swing.JComponent.paint(Unknown Source) where line 54 refers to pie[0].g = (Graphics2D) g; – dkregen Nov 04 '15 at 18:34
  • see http://stackoverflow.com/a/17871842/635678 for help. what is line 54 in main.java ? – Dan O Nov 04 '15 at 18:35
  • @DanO : I've just edit my comment. – dkregen Nov 04 '15 at 18:50

1 Answers1

0
private Block[] pie = new Block[5];

You create an array of size 5, but you have not added any Block's to the Array,

pie[0].g = (Graphics2D) g;
pie[0].draw();

So when you try to reference the object at index 0, you get a NPE.

So at the start of your constuctor you might add:

pie[0] = new Block();

Also, your draw method should be defined something like:

public void draw(Graphics g)

then in your painting code you would use:

pie[0].draw(g);

That is you don't need to store a Graphics object in your Block class. Pass the Graphics object to the method.

camickr
  • 321,443
  • 19
  • 166
  • 288