Search code examples
javaintellij-ideacorretto

Images not loading after creating Jar


im wring a simple program and my images load in fine in the project but as soon as i export it into a jar file none of them load. i have little to no experiance creating artifacts or jar files.

project structure:

project:

    src: 
       myclass1, myclass2...

    res:
        image1.png image2.png...

im using Toolkit.getdefaultToolkit to load in images

in my class i am loading the images in the constructor by writing myImage = toolkit.getImage("res/image1.png"); this works perfectly fine in the project. does not work in the jar

i have also tried myImage = toolKit.getImage("image1.png"); which does not work in the project or while opening the jar

i know toolkit is not the best way to go about loading images but i would like to know how i can fix this issue while using toolkit.

ive even tried using the absolute path to a folder on my desktop and once again they load in fine in my project but they do not get loaded when opening the jar. please help ive tried everything. thanks

(btw) if i open the jar file in intellij the images load but if i open the jar file in finder or from my desktop they do not. i want to be able to send the finished project to someone


Solution

  • The toolkit.createImage(String) method takes in a string, and interprets it as a path, looking for a file at that path. An entry in a jar file is not itself a file. It is therefore impossible to use this method to read image files that are in a jar.

    However, that's not the only createImage method. There's also toolkit.createImage(URL) and that is the one you want.

    SomeClass.class.getResource("something.png")
    

    This expression works on any class (Foo.class gets you the class instance for Foo, and all class instances have the getResource method), and will look for the named entry in the exact same place SomeClass.class (the file) lives. If SomeClass.class currently lives in a jar file, then that's where it'll look.

    Thus, ensure that img.png is in the same place your class file is (ensure it is jarred along with the rest), and that will work. You can also ask for e.g. SomeClass.class.getResource("/foo/bar/img.png"); this will then look from the 'root' of where SomeClass is. So if you have a jar such that if you run jar tvf thatjar.jar and you get:

    ....
    /com/foo/yourpackage/SomeClass.class
    ....
    /foo/bar/img.png
    

    then /foo/bar/img.png works.

    thus: Once you know where you put that stuff in your jar file:

    toolkit.createImage(YourClass.class.getResource("image1.png"))
    

    is what you're looking for.