Search code examples
javaimagebufferedimage

Load Java Image inside package from a class in a different package


I have a Java project called MyProject. I have a few different packages (keeping names simple for the purpose of this question), as follows:

src/PackageA
src/PackageA/PackageAa
src/PackageA/PackageAa/PackageAaa
src/PackageB
src/PackageB/PackageBa
src/PackageB/PackageBa/PackageBaa

I have a class

src/PackageA/PackageAa/PackageAaa/MyJavaFile.java

And I have an image

src/PackageB/PackageBa/PackageBaa/MyImage.png

Inside of MyJavaFile.java, I would like to declare an Image oject of MyImage.png

Image img = new Image(....what goes here?...)

How can I do this?


Solution

  • 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.)