Search code examples
javaeclipsegraphicsembedded-resource

how does one access a picture from within a jarfile? ie what would i use for a directory string?


Alright, so this is probably a really beginner problem here, but I've never actually used pictures inside my src folder. I always have linked my pictures to some folder like C:\\Resource\\Logo.png. I took a screenshot of how I've worked my directories. Basically I'm trying to get from net.mousemaze.Textures.java to Resource.Font\FontA.png.

Location of font image

Also, it may be worth noting that I am currently running on fedora 17.

the class that gets the images is pasted at http://pastebin.com/KMVac7mg

also, the directories have been rearranged (screenshot updated) so i dont have to deal with going back a directory. Even so, it is not working.


Solution

  • If you look at the docs, there is a method called "createImageIcon" which works within jar files:

    /** Returns an ImageIcon, or null if the path was invalid. */
    protected ImageIcon createImageIcon(String path,
                                               String description) {
        java.net.URL imgURL = getClass().getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL, description);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }
    

    See if you can edit that code to fit your purpose.

    Edit: Link: http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html