0

Whenever I run this I get an error:

"Exception in thread "main" java.lang.NullPointerException at anime.re.drawShape(re.java:17) at anime.re.main(re.java:12)"

I am not passing a null reference, what is the problem?

import javax.swing.JFrame;
import java.awt.Graphics;

public class re {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(400, 400);
        Graphics g = frame.getGraphics();
        drawShape(g);
        frame.setVisible(true);
    }

    public static void drawShape(Graphics g) {
        g.drawOval(0, 0, 100, 100);

    }
}
zangw
  • 43,869
  • 19
  • 177
  • 214

1 Answers1

1

Use the paint method for Graphics2D instead of making your own method. also your null pointer exception is coming from trying to draw before setting up your jpanel or making your jframe visible.

public class example extends JPanel{

public static void main(String[] args){
    JFrame frame = new JFrame("Example");
    example main = new example();
    int miliSecs = 25;

    frame.add(main);

    frame.setSize(640, 480);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

    frame.repaint();//here is the call to the paint method
}
    public void paint ( Graphics g ){
    //paints the screen
    g.setColor(Color.BLACK);
    g.fillRect(0,0,640,480);
    }
}

This way, you also call the update() method which clears the screen every frame along with your paint() method.

Ryan
  • 1,972
  • 2
  • 23
  • 36