I am currently working on an image viewer program and am having a bit of difficulty displaying the Image objects themselves. Basically, I created an ImagePanel class with a paintComponent(Graphics g) method. When I use this, the image does in fact show up in the ImagePanel panel, but I am still getting a null pointer exception and a stack trace. I have read a few threads on the getGraphics() returning null issue, but the thing is that the ImagePanel IS added to a JFrame which is packed and set to visible. It's heartening that it's showing the image but the stack trace is worrying!
My code is pretty massive so here are some relevant bits:
From the PhotoGUI class:
Any help or suggestions would be VERY much appreciated!
Thanks in advance.
Actually, thanks a lot for your reply Swastik, but I just fixed it!
For anyone that does come across this in the future, all I had to do was replace the getGraphics() parameter with viewPane.getGraphics(), where viewPane is an instance of ImagePanel. Gotta love a simple solution.
Sara Savoie wrote:For anyone that does come across this in the future, all I had to do was replace the getGraphics() parameter with viewPane.getGraphics(), where viewPane is an instance of ImagePanel. Gotta love a simple solution.
For anybody reading this that is NOT the proper solution. You should never (in my experiences) use the getGraphics() method.
The proper solution is to modify the the setImage() method to be:
In fact given that the ImagePanel paint the image at it original size there is even no need to create a custom component.
The easier solution is to use a JLable and and ImageIcon. Then to change the image you change the ImageIcon and everything is repainted automatically.
Joined: Nov 27, 2009
Thank you for your reply. I have tried your method but now it seems to be printing a stack trace and not painting anything at all!
To elaborate, we have to create a custom "Photo" object- the details are irrelevant but it does have a getImage() method that returns an image object. Below is how I went about implementing your suggestion:
My stack trace is as follows:
java.lang.NullPointerException at javax.swing.ImageIcon.<init>(Unknown Source)
at ca.ubc.cs.cpsc211.photo.PhotoGUI.displayPhoto(PhotoGUI.java:289) //on this line: imageSpace.setIcon(new ImageIcon(p.getImage()));
at ca.ubc.cs.cpsc211.photo.PhotoGUIDriver.main(PhotoGUIDriver.java:12) //on this line: gui.displayPhoto(p);
Any further help is much appreciated. Thanks again.
Joined: Jun 13, 2009
The problem is in your Photo class and I have no idea what is does. It looks like you have a null image.