Search code examples
javagraphicsjpanelawtpaintcomponent

Trying to draw a simple rectangle with JPanel, but nothing is showing up


I am currently reading the book "Head First Java". The book is amazing and I am really enjoying reading it. But I have come to an abrupt halt. The book was going through GUI programming with the swing library, which turned out to be easier than I thought it would be. After the GUI portion of the chapter the book introduced drawing graphics, with the awt library and graphics objects. And this is where I am stuck. The following is my code, which compiles just fine but does not seem to want to render the rectangle.

import java.awt.*;
import javax.swing.*;

public class DrawTest
{
    JFrame frame;

    public static void main(String[] args)
    {
        DrawTest test = new DrawTest();
        test.go();
    }

    public void go()
    {
        frame = new JFrame();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 800);
        frame.setVisible(true);
        frame.setResizable(false);
    }
}

class DrawPanel extends JPanel
{
    public void paintComponent(Graphics g)
    {
        g.setColor(Color.green);
        g.drawRect(70, 70, 200, 200);
    }
}

What am I doing wrong? It is most likely very obvious, but I am not seeing. I would very much appreciate a thorough answer, I am new to Java so I would like to understand fully.

Thanks in advance!


Solution

  • You will need to instantiate a DrawPanel and add it to frame in DrawTest. First include a constructor for DrawPanel, then add these lines in the go() method:

    DrawPanel panel = new DrawPanel();
    frame.add(panel);