Reputation:
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?
Upvotes: 1
Views: 88
Reputation: 11153
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
Upvotes: 0
Reputation: 3409
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.
Upvotes: 3