This discussion is archived
1 Reply Latest reply: Nov 12, 2007 10:43 PM by 807603 RSS

Image Filename - Relative Location

807603 Newbie
Currently Being Moderated
Hi, I am a pretty new programmer, and ran into a situation where I feel pretty stuck. I have a program that involves putting an image on the screen. Currently, I have a static filename: "C:/Program Files..." I want to be able to move a folder with my program and the image around onto multiple computers, but I don't want to have to change the filename every time I do so. Imagine that my the java file is in the same folder as the picture. Is there a method I can call to retrieve the location of file I am running? (If it matters, it is an application)

Please let me know if there is any more information i need to provide.

Thanks in advance for any help you can give.

private class MainPanel extends JPanel {
     public void paintComponent(Graphics g) {
          Graphics2D g2D = (Graphics2D)g;
          Image i = Toolkit.getDefaultToolkit().getImage("C:/Program Files/Folder/Picture.jpg");
          g2D.drawImage(i, 100, 210, this);}
  • 1. Re: Image Filename - Relative Location
    807603 Newbie
    Currently Being Moderated
    There is a class called Class which has a method getResource(). This method returns a URL based on the name you supply as an argument. This URL can be used to load resources like images - for instance there is a version of the toolkit getImage() method that uses a URL rather than a filename.

    The API documentation describes precisely how resources are found but, roughly speaking, they are located in the same place as the class file. This can "move around", or even be placed inside a jar file and the image will still load.

    Class provides a static method that lets you get an instance of Class (to load resources with) based on the class name: like
    Class cls = Class.forName("MainPanel");
    Or you can use getClass() with an instance of a particular class
    public void paintComponent(Graphics g) {
        Image i = Toolkit.getDefaultToolkit().getImage(getClass().getResource("Picture.jpg"));
        // etc
    (Haven't tested this - and I don't think you should really load the image every time paintComponent() is called. All sorts of exceptions can be thrown, so you may want to break that long line up a bit.)