Search code examples
javagraphics2djava-2d

Drawing Rectangle From Another Class


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.


Solution

  • 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.