Reputation: 1212
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?
Upvotes: 4
Views: 16574
Reputation: 347184
There are any number of 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
Upvotes: 6
Reputation: 1158
I know this is an old post, but I had the same issue on my project and fixed it by giving the full path in the ImageIcon
definition, instead of just the path from the project. I.e.
ImageIcon im = new ImageIcon("C:/your/image/file/path/banner.png);
It solved the issue for me, but I do recognise that this is not a valid long-term solution, since it will only work on the developer's machine and I'm not sure if portability would be an issue.
Hope I have helped somebody.
Upvotes: 0
Reputation: 4676
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"));
Upvotes: 1
Reputation: 135
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.
Upvotes: 4
Reputation: 1612
There's a lot of things that could be going on here and it's hard to tell without more code. Based on the short snippet above (and assuming everything else is correct) you should check the image load status of the ImageIcon using the getImageLoadStatus() method. If it returns MediaTracker.COMPLETE then you're good to go and the error is somewhere outside this code. If it's anything but COMPLETE then you are having some sort of issue in loading the image. Maybe it's not in the path or classpath?
Upvotes: -1