Question

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?

Was it helpful?

Solution

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"));

OTHER TIPS

Do you add images folder under build path?

if you use eclipse, add this folder to build path. enter image description here

then you could find this picture in your code:

File file = new File("./images/test.png");
System.out.println(file.exists());

try this by creating proper objects it give you clear image of processing and you can short your project later on. First try with C:/

JPanel panel = new JPanel(); 
ImageIcon icon = new ImageIcon("C:/Logo1.png"); 
JLabel label = new JLabel(); 
label.setIcon(icon); 
panel.add(label); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top