Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

What's wrong with this code

  Asked By: Thomas    Date: Apr 07    Category: Java    Views: 902
  

myToolkit = Toolkit.getDefaultToolkit();
ruler = myToolkit.getImage("ruler.jpg");
Graphics g = jPanel2.getGraphics();
g.drawImage(ruler, 0, 0, jPanel2);


Compiles fine (JBuilder 7, JSDK 1.4.1.03) put the last line provokes
a NullPointer exception when the program is run

..have tried putting the jpg in various maps (source, bin dir etc)

Share: 

 

1 Answer Found

 
Answer #1    Answered By: Oliver Evans     Answered On: Apr 07

maybe myToolkit.getImage is returning a null,to make sure, type this:
System.out.println("ruler="+ruler);
but dont write ruler.toString(), cos if ruler is null, then its like
typing :
null.toString()

and then passing null (ruler) to g.drawImage(null),,,,,,, will throw
an exception!

so the solution is , put
if(ruler==null)
{
//doAlternativeActionOrPicture();
}
else
{ Graphics g = jPanel2.getGraphics();
g.drawImage(ruler, 0, 0, jPanel2);
}

 
Didn't find what you were looking for? Find more on What's wrong with this code Or get search suggestion and latest updates.




Tagged: