1

I am having trouble with this code:

package shapes;

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

public class Shapes extends JFrame {

public static void main(String[] args) {
    doDrawing();
}

private static void doDrawing() {
    Graphics2D g = null;
    // TODO Auto-generated method stub
    Graphics2D g2d = (Graphics2D) g;
     g2d.drawLine(20, 20, 100, 100);
}

}

But when i run it i get:

Exception in thread "main" java.lang.NullPointerException
at shapes.Shapes.doDrawing(Shapes.java:17)
at shapes.Shapes.main(Shapes.java:10)

How shall i fix this problem?

justcurious
  • 839
  • 3
  • 12
  • 29
  • `Graphics2D g = null;` [see](https://docs.oracle.com/javase/tutorial/uiswing/painting/closer.html) – Andrew Tobilko Oct 23 '15 at 13:43
  • 1
    Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – khelwood Oct 23 '15 at 13:45

2 Answers2

3

You set g to null:

Graphics2D g = null;

and then cast this null and assign to g2d

Graphics2D g2d = (Graphics2D) g;

and then call a method of a null object instance.

Michał Szydłowski
  • 3,261
  • 5
  • 33
  • 55
0

You're trying to access a null element:

Graphics2D g = null;

And then you're trying to do something like this:

Graphics2D g2d = (Graphics2D) null;

That's why you're getting NullPointerException.

I'm not really into Graphics class, but, based on this example from docs, I made this code

import java.awt.*;
import java.applet.Applet;
import java.awt.geom.Rectangle2D;
import javax.swing.*;

public class Shapes extends JApplet {
    public static void main(String[] args) {
        JApplet app = new Shapes();
        JFrame f = new JFrame("Example");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        app.init();
        app.start();
        f.add("Center", app);
        f.pack();
        f.setVisible(true);
    }

    Shapes() {
    }

    public void paint(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawLine(20, 20, 100, 100);
    }
}

It draws the line you provided on your code.

I hope it helps

Frakcool
  • 10,915
  • 9
  • 50
  • 89