When using images, you want to load them through URL with Class.getResource()
, which returns a URL. Passing a String the the ImageIcon
will cause the image to be looked up through the file system. Though this may work during development in your IDE, you'll come to find out it won't work at time of deployment. Better make the changes now. To use this method, you want do this
ImageIcon icon = new ImageIcon(Images.class.getResource("/Users/georgebastow/Picture/background.jpg"));
For this to work though, you file structure needs to look like this
ProjectRoot
src
Users
georgebastow
Picture
background.jpg
A more common approach is just to put the image a reousrces folder in the src
ProjectRoot
src
resources
background.jpg
And use this path
ImageIcon icon = new ImageIcon(Images.class.getResource("/resources/background.jpg"));
When you build, your IDE will transfer the images to the class path.
Side Note
- Don't paint on top level containers like
JFrame
. Instead useJPanel
orJComponent
and override thepaintComponent
method. if usingJPanel
, you should also callsuper.paintComponent
in thepaintComponent
method. Run you Swing Apps from the Event Dispatch Thread like this
public static void main(String[] args) { SwingUtiliities.invokeLater(new Runnable(){ public void run() { new Images(); } }); }
See Initial Thread
Don't call
Thread.sleep()
. When running from the EDT (like you should), you will block it. Instead use ajava.swing.Timer
if it's animation you're looking for. Even if it's not animation, still use it! See this example forTimer
program.- Also as @mKorbel mentioned, you never add anything to the frame.
UPDATE
Run this example. I also forgot to mention, when you paint on JPanel
you also want to override the getPreferredSize()
. This will give your panel a size.
src/resources/stackoverflow5.png
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestImage {
public TestImage() {
JFrame frame = new JFrame("Test Image");
frame.add(new NewImagePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public class NewImagePanel extends JPanel {
private BufferedImage img;
public NewImagePanel() {
try {
img = ImageIO.read(TestImage.class.getResource("/resources/stackoverflow5.png"));
} catch (IOException ex) {
System.out.println("Could not load image");
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(600, 600);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestImage();
}
});
}
}