Cannot Understand The Exception
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 :
Exc开发者_开发百科eption 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 NullPointerException
here.
For example:
//created a variable holding a reference to an object of type JPanel
JPanel p;
//now the value of p is null. It's not pointing to anything
//created an object of type JPanel and assigned it to p
p=new JPanel();
//now p is not null anymore, it's pointing to an instance of JPanel
Well, you didn't do that for Graphic
object g
.
You haven't initialized Graphics g
You should implement a paint
method and move the logic for drawing the background into that (see the JavaDoc on paint)
Always go to the line where the NullpointerException occured and see which objects are used on that line. In this case it was only the Graphic object "g" that was in use. Then try to figure out why "g" has a null reference. As you can see "g" was never instantiated, it was only declared. You have to new it up.
This works fine :
Since you are using graphics in swing
, this will help.
import java.awt.*;
import javax.swing.*;
class tester_1 extends JPanel{
JFrame fr;
JPanel p;
tester_1() {
buildGUI();
}
public void buildGUI() {
fr=new JFrame();
p=new JPanel();
p.setBackground(Color.red);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawOval(18,45,78,39);
g.fillOval(18,45,78,39);
}
}
class tester {
tester() {
JFrame frm=new JFrame();
tester_1 t=new tester_1();
frm.add(t);
frm.setVisible(true);
frm.setSize(500,500);
}
public static void main(String args[]) {
new tester();
}
}
The exception that you have been getting is because you didn't initialize the variable g
.
精彩评论