Search code examples
javaswingembedded-resource

how to include images in java app within local directory?


I am trying to include image in java application on windows 7. So far it takes valid path as :

ImageIcon F1Icon = new ImageIcon("C:\\ServiceCenter\\nine.jpg");

This works fine but it requires my application to create such directory on different machine.i want to load image by keeping it within local directory of application .

like when i do following,

ImageIcon F1Icon = new ImageIcon("nine.jpg");

image does not load. any solutions?


Solution

  • Do you use eclipse or similar editors for your coding/debugging? If yes, the working directory of your application may be different than what you think. For example, the default running path for eclipse is the project directory, not the "src" directory.

    You can also navigate between directories via relative addresses using the convention for current folder: "./" and parent folder: "../" (without quotes).

    For example, if the working directory is: C:/Documents/myproject/src and your image file is at: C:/Documents/myproject/resource/nine.jpg,

    you can do:

    ImageIcon F1Icon = new ImageIcon("../resource/nine.jpg");
    

    I hope it helps.