Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 905
CodeGuy Avatar asked Aug 28 '12 06:08

CodeGuy


People also ask

Can we have package inside package in Java?

Yes, you can create a package inside a package in Java. It is called sub-package.

Can a Java class be part of a package?

All classes/interfaces in a file are part of the same package. Multiple files can specify the same package name.

Can we use more than one package in Java?

No, you can't do that.


2 Answers

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

like image 185
Jon Skeet Avatar answered Sep 30 '22 19:09

Jon Skeet


you can use relative path since the the relative path is project folder.

 ImageIcon img = new ImageIcon("src/PackageB/PackageBa/PackageBaa/MyImage.png");
like image 43
mohamed abdallah Avatar answered Sep 30 '22 19:09

mohamed abdallah