javaswinggraphicsnullpointerexceptionpanels

Problems using Graphics with Panels in the Java Swing Library


Hey everyone, I am trying to run the following program, but am getting a NullPointerException. I am new to the Java swing library so I could be doing something very dumb. Either way here are my two classes I am just playing around for now and all i want to do is draw a damn circle (ill want to draw a gallow, with a hangman on it in the end).

package hangman2;

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

public class Hangman2 extends JFrame{
    private GridLayout alphabetLayout = new GridLayout(2,2,5,5);
    private Gallow gallow = new Gallow();

    public Hangman2() {

        setLayout(alphabetLayout);

        setSize(1000,500);
        setVisible( true );

    }

    public static void main( String args[] ) {   
     Hangman2 application = new Hangman2();
     application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    }
}


package hangman2;

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

public class Gallow extends JPanel {
    private Graphics g;

    public Gallow(){
        g.fillOval(10, 20, 40, 25);       
    }
}

The NullPointerException comes in at the g.fillOval line.

Thanks in advance,

Tomek


Solution

  • You're getting NPE because g is not set, therefore, it's null. Furthermore, you shouldn't be doing the drawing in the constructor. Overload paintComponent(Graphics g) instead.

    public class Gallow extends JPanel {
        public paintComponent(Graphics g){
            g.fillOval(10, 20, 40, 25);       
        }
    }
    

    I'd also look into BufferedImage.