How would I draw on a JPanel to then be shown on a JFrame?

I've tried to research how Java's 2D rendering works, but I could never understand it. Here is the code in my main class:

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main{

    public static void main(String args[]) {
        JFrame frame = new JFrame();
        frame.setSize(new Dimension(500,500));
        frame.setTitle("JFrame testing");
        Frame panel = new Frame();

And then here is for the JPanel class:

import java.awt.Graphics;

import javax.swing.JPanel;

public class Frame extends JPanel{
    private static final long serialVersionUID = 1L;

    public Frame() {
        Graphics g = this.getGraphics();
        g.drawRect(0, 0, 100, 100);

I am also getting this exception, but I'm not sure what it means:

Exception in thread "main" java.lang.NullPointerException
    at Frame.<init>(
    at Main.main(

I'm basically just trying to draw a rectangle onto a panel to be shown on the frame I've created. I've heard about the paintComponent method, but I also don't fully understand that.

1 answer

  • answered 2018-02-13 03:19 John Joe

    You should Never use getGraphics() of a Component.

    Try below code

     public void paintComponent(Graphics g) {
            g.drawRect(0, 0, 100, 100);


    "why is super.paintComponent(g); called again inside the method?"

    The documentation of paintComponent says it pretty well:

    if you do not invoker super's implementation you must honor the opaque property, that is if this component is opaque, you must completely fill in the background in a non-opaque color. If you do not honor the opaque property you will likely see visual artifacts.