Connecting Tech Pros Worldwide Forums | Help | Site Map

Problem painting an image

Newbie
 
Join Date: May 2009
Posts: 26
#1: Oct 21 '09
Hey, I've got some code that is supposed to paint part of an image on a JPanel. Unfortunately, when I run it, I get a nullPointer Exception.

Expand|Select|Wrap|Line Numbers
  1. public void paintMap()
  2.     {
  3.         Graphics g = this.getGraphics();    //Create a new Graphics object.
  4.         Graphics2D g2d = (Graphics2D) g;    //Cast it to a Graphics2D object (Has more options)
  5.         Image spaceImages = Toolkit.getDefaultToolkit().getImage ( "stars.png" );
  6.         System.out.println(spaceImages.getWidth(null)); //Returns -1. Is that a problem?
  7.         g2d.drawImage(spaceImages, 0, 0, 50, 50, 0, 0, 50, 50, null);
  8.                //more code
The error occurs on the last line of code (Line 7), but I wonder if I'm not creating the image correctly, as when I try to get the width of the image it returns -1 (on line 6). Any thoughts?

jx2 jx2 is offline
Familiar Sight
 
Join Date: Feb 2007
Location: Bristol UK
Posts: 227
#2: 3 Weeks Ago

re: Problem painting an image


Are you sure that the file is in a correct folder?
you can try this:
Expand|Select|Wrap|Line Numbers
  1. BufferedImage img = ImageIO.read(new File("imagepath.jpg"));
  2.  
I know this one is working, and you'll get IOException if it cannot open a file

regards jan
Newbie
 
Join Date: May 2009
Posts: 26
#3: 3 Weeks Ago

re: Problem painting an image


Thanks. I think that Eclipse was unable to see it.
Reply


Similar Java bytes