I want to set an image icon in a panel.I am trying to do like this ;
JLabel label = new JLabel(new ImageIcon("logo.jpg"))
panelHeader.add(label);
add(panelHeader);
But the image is not showing.Any suggestion what i am doing wrong?
I want to set an image icon in a panel.I am trying to do like this ;
JLabel label = new JLabel(new ImageIcon("logo.jpg"))
panelHeader.add(label);
add(panelHeader);
But the image is not showing.Any suggestion what i am doing wrong?
The new ImageIcon()
constructor just creates an uninitialized image icon. You must invoke the createImageIcon()
method that returns ImageIcon
source to assign to your also created ImageIcon
object.
ImageIcon icon = createImageIcon("logo.jpg", "my logo");
JLabel label = new JLabel(icon);
new ImageIcon("logo.jpg")
The String
based constructor for an ImageIcon
presumes the string represents a file path. Since this is an image that is added to a panel, by run-time, it will likely be inside a Jar and not accessible as a File
. For an embedded application resource, the only viable access is by URL
. The URL might be obtained from something like:
URL logoUrl = this.getClass().getResource("/logo.jpg");
Note the leading /
. That tells the JRE to search for the resource on a path relative to the root of the class-path, as opposed to a path relative to the package of the class that loads it.
You've got two good answers on creating the ImageIcon
. You should also look at the layout of the container to which you add the label. This example uses FlowLayout
, the implicit default for JPanel
.