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?
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