How to set image on jlabel from project folder?

user3506824 picture user3506824 · Apr 8, 2014 · Viewed 8.2k times · Source

I am trying to make a Java desktop application.

I want to set an image on JLabel.

I am using NetBeans.

From my project folder, my directory structure is:

F:/>MARKET
    |
    |___src
    |
    |___lib
    |
    |___src
    |      |
    |      |__defaultpackage
    |                       |
    |                       demo.java
    |__images
            |
            |
            Logo1.png

I used following code:

jLabel4 = new JLabel(new ImageIcon("images/Logo1.png"));

It is not working, how can I get my output?

Answer

MadProgrammer picture MadProgrammer · Apr 8, 2014

If you want the images included within the Jar, then you will need to move the images folder into the src directory.

This will then require you to use something more like...

jLabel4 = new JLabel(new ImageIcon(getClass().getResource("/images/Logo1.png")));

To the load image.

If you want the images to remain external to your program Jars (and remain open to the file system), then you need to ensure that the execution context for the program is within the context of the project folder (at the same level as the src and images directory).

This can be done via the Project Properties -> Run properties. By default, when run, the program will execute from the context of the running projects folder.

Properties

If you're wanting to use external resources you can do two things to check for them...

One, create a File using the same path as the external resource you want to load and check to see if it exists...

 if (new File("images/Logo1.png").exists()) {...

Or if you can't seem to get it to work, check your current running context with...

System.out.println(new File(".").getCanonicalPath());

Which will tell your current working directory (beware this will throw an IOException).

You can also use the system property user.dir

System.out.println(System.getProperty("user.dir"));