I’ve been programming in Java for a little while now but have never really done much with the swing packages. I am currently designing a GUI for an A.I. call and response program despite the relative complexity (for me at least) of the rest of what I have been doing, this image loading problem, which seemed extremely simple to implement is stumping me.
The below classes work if not in a package, which is what really confuses me. I’ve tried several different implementation suggestions (one from Head First Java, one from the docs.oracle.com tutorials and another using what http://leepoint.net/notes-java/GUI-lowlevel/graphics/45imageicon.html suggests).
package CaRII;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class P{
public static void main(String [] args){
P p = new P();
p.go();
}
public void go(){
JFrame frame = new JFrame("CaRRI: Call and Response Intelligent Improviser");
PBackground mainPanel = new PBackground();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(800,500);
frame.setVisible(true);
}
}
package CaRII;
import java.awt.*;
import javax.swing.*;
public class PBackground extends JPanel{
public Image backgroundImage;
public PBackground(){
backgroundImage = Toolkit.getDefaultToolkit().createImage("CaRIIBackGround.jpg");
}
public PBackground(LayoutManager layout){
backgroundImage = Toolkit.getDefaultToolkit().createImage("CaRIIBackGround.jpg");
}
public void paint(Graphics g){
g.drawImage(backgroundImage,0,0,null);
}
}
Like I said the strange thing is that it doesn’t display the image if these two classes are in package CaRRI; but if I compile and run them without the package declaration they run fine(albiet the image not loading until the window resizes… but i have seen solutions online for that so I will be able to sort that once I get it loading within the package). I have been writing in XCode and JEdit and the image is stored within the package folder inside source (/src/CaRII/P.java … /src/CaRII/CaRIIBackGround.jpg), I have also tried storing the image in a resources folder within /src/ and using
ImageIcon(getClass().getResource("/resources/CaRIIBackGround.jpg)).getImage();
but that that causes another error when run
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:181)
at CaRII.PBackground.<init>(PBackground.java:19)
at CaRII.P.go(P.java:21)
at CaRII.P.main(P.java:15)
Any help would be much appreciated as despite its simplicity this has been stumping me all morning and I have a lot of other classes to write.
Thanks
(Heres the image(im a new user so i cant post images but this is a link to it))
http://imageshack.us/photo/my-images/189/cariibackground.jpg
1 Answer