Click here to Skip to main content
15,435,939 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm creating function which draws a rect on the screen.

The code is below in What I have tried

My Error

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.awt.Graphics.fillRect(int, int, int, int)" because the return value of "javax.swing.JPanel.getGraphics()" is null
at myCanvas.fillRect(
at Main.main(

For some reason the `super.getGraphics()` is returning null, and I'm unable to fix it.

Similar type of usage of graphics like this, I saw in this [website][1] in example program 2.

How should I fix this error?

What I have tried:

public class myCanvas extends JPanel{
    // some code
    public void fillRect(int w, int h){
        super.getGraphics().fillRect(penX,penY, w, h);
    // some code
Updated 30-Nov-21 21:27pm

1 solution

This SO post: java - Drawing an object using getGraphics() without extending JFrame - Stack Overflow[^] explains that getGraphics() methods is not to be used; you should override the paintComponent() method, as explained in the first solution.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900