"The player.gif file is two pictures in one file, and is saved in the same directory as the java file."
Images should be loaded from the class path. Passing a String to the ImageIcon
loads the image from the file system, in which case your path wont work.
To load from the class path just do this
ImageIcon img = new ImageIcon(getClass().getResource("player.gif"));
As long as your file is in the same package as your .java file as you've described, the image should get built into your class path.
You can also use the ImageIO
class to read the image, which will throw an exception if the image can't be loaded, which will throw a FileNotFoundException
so you know your path is wrong
Image img;
try {
img = ImageIO.read(getClass().getResource("player.gif"));
} catch (IOException ex) {
ex.printStackTrace():
}
Also, you should be calling super.paintComponent(g)
in your paintComponent
method, and as good practice use @Override annotations when necessary
@Override
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
Side Note
When painting on
JPanel
you should overridegetPreferredSize()
which will give theJPanel
a preferred size, then you can justpack()
your frame, which you should be doing.@Override public Dimension getPreferredSize() { return new Dimension(400, 400); }
Also
paintComponent
should beprotected
and notpublic