Java image not showing?

10,500

Solution 1

Try ImageIcon im = new ImageIcon(new File("banner.png")); If you're using eclipse, put it in the root folder, not the src folder. The root folder has the src folder and the bin folder.

Solution 2

There are any possible issues, but the likely one is, the location of the image is not within the same context as where the application is being executed from.

Let's say, main.java lives in some directory (lets just say "path/to/class" for argument sake), then when you execute you main.java, the path to the images would become something like /path/to/class, meaning you should be using using something like...

ImageIcon im = new ImageIcon("path/to/class/banner.png"); 

This also assumes that the image hasn't being Jar'ed yet, as ImageIcon(String) expects a path to a file on the file system.

If the program has being Jar'ed then you won't be able use ImageIcon(String), as the banner.png is no longer a file, but a resource, then you would need to use something like...

ImageIcon im = new ImageIcon(getClass().getResource("/path/to/class/banner.png"));

Where /path/to/class is the package where main.java lives.

In either case, I would recommend that you use ImageIO.read instead, as this will actually throw an IOException when something goes wrong, where ImageIcon tends to fail silently...

Take a look at Reading/Loading an Image for more details

Solution 3

If you create a folder called images (or whatever name you prefer) in your source directory, and then place the banner.png file in that folder you can then use the following code.

ImageIcon im = new ImageIcon(this.getClass().getResource("/images/banner.png")); 
Share:
10,500
lecardo
Author by

lecardo

Updated on June 04, 2022

Comments

  • lecardo
    lecardo almost 2 years

    Having a issue trying to display my logo. The picture is saved in the same folder as main.java

        ImageIcon im = new ImageIcon("banner.png"); 
        JLabel bam = new JLabel(im); 
    
        grid.add(bam);
    

    Is there a problem in my syntax?