Walker
Walker

Reputation: 11

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.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("JFrame testing");
        frame.setVisible(true);
        Frame panel = new Frame();
        frame.add(panel);
    }
}

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);
        this.paintComponent(g);
    }
}

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

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

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.

Upvotes: 0

Views: 284

Answers (1)

John Joe
John Joe

Reputation: 12803

You should Never use getGraphics() of a Component.

Try below code

 public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawRect(0, 0, 100, 100);
        //this.paintComponent(g);
    }

Edit

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

Upvotes: 1

Related Questions