import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
@SuppressWarnings(\"serial\")
public class Picture e
Try:
ImageIcon image = new ImageIcon(getClass().getResource("TestImage.jpg"));
See How to Use Icons tutorial for more details, in particular Loading Images Using getResource section.
the image is in the same folder as my project package folder
That's it.
As written, your program looks for the image in the current working directory, not the package hierarchy.
From the Javadoc for the constructor taking String, it reads the image from the specified filename, as desired. However, when you specify a relative path, that means to read relative to the working directory that the application is running in.
To work around this, you have 2 options:
Specify the image filename relative to the working directory your IDE runs your program in. I believe Eclipse runs applications in the project root directory, and the source package hierarchy is rooted at src
. In this case it'll work if you specify src/TestImage.jpg
. The disadvantage is that if you ever run your program from a different directory, you'll have to move the image file along with it. This is inconvenient for distribution/packaging, because you can't just drop the JAR file and have it run.
Use Java's resource loader to load the image file from the package hierarchy. To do this, first use
getClass().getResource("TestImage.jpg")
to get a URL for the image (relative to the package root). See that ImageIcon has a constructor that accepts a URL to read the image from. So you should read the image using
new ImageIcon(getClass().getResource("TestImage.jpg"))
The advantage of being relative to he package hierarchy is that the program can be run from any location, and the image can be bundled with your app in a single JAR file.
Aside: it's best practice to create a package in which you place both code and resources (rather than just placing them in the package root). In that case, pass "com/example/someapp/TestImage.jpg"
instead.