This is the code :
import java.awt.*;
import javax.swing.*;
class tester {
JFrame fr;
JPanel p;
Graphics g;
tester() {
buildGUI();
}
public void buildGUI() {
fr=new JFrame();
p=new JPanel();
p.setBackground(Color.red);
g.setColor(Color.black);
g.drawOval(18,45,78,39);
g.fillOval(18,45,78,39);
fr.add(p);
fr.setVisible(true);
fr.setSize(500,500);
}
public static void main(String args[]) {
new tester();
}
}
These are the exceptions produced when i try to run the code :
Exception in thread "main" java.lang.NullPointerException
at tester.buildGUI(tester.java:17)
at tester.<init>(tester.java:10)
at tester.main(tester.java:26)
Why do i get these exceptions?
How can i solve it.
You never created object
g– you just declared it.Until you create an object and assign it to the variable holding a reference to it, the value of that variable is
null.That’s why you are getting
NullPointerExceptionhere.For example:
Well, you didn’t do that for
Graphicobjectg.