Load Java Image inside package from a class in a different package
you can use relative path since the the relative path is project folder.
ImageIcon img = new ImageIcon("src/PackageB/PackageBa/PackageBaa/MyImage.png");
/folderB/folderBa/folderBaa/MyImage.png
The image can stored into a project folder location .eg: /images/MyImage.png
Then try:
Image img = new Image(/images/MyImage.png);
Using a file path is not possible when running a program that's in a jar file, especially if the program is being loaded as an applet or WebStart application then you can use ClassLoader to get image.
use the following code to load the images:
ClassLoader cldr = this.getClass().getClassLoader();
java.net.URL imageURL = cldr.getResource("/PackageB/PackageBa/PackageBaa/MyImage.png");
ImageIcon aceOfDiamonds = new ImageIcon(imageURL);
You could either call Class.getResource
and specify a path starting with /
, or ClassLoader.getResource
and not bother with the /
:
URL resource = MyJavaFile.class
.getResource("/PackageB/PackageBa/PackageBaa/MyImage.png");
or:
URL resource = MyJavaFile.class.getClassLoader()
.getResource("PackageB/PackageBa/PackageBaa/MyImage.png");
Basically Class.getResource
will allow you to specify a resource relative to the class, but I don't think it allows you to use ".." etc for directory navigation.
Of course, if you know of a class in the right package, you can just use:
URL resource = SomeClassInPackageBaa.class.getResource("MyImage.png");
(I'm assuming you can pass a URL
to the Image
constructor in question. There's also getResourceAsStream
on both Class
and ClassLoader
.)