3

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?

sohel14_cse_ju
  • 2,481
  • 9
  • 34
  • 55
  • 2
    Please edit your question to include an [sscce](http://sscce.org/) that show the layout of the container to which you add the label. – trashgod Apr 22 '12 at 09:47
  • Which IDE you are using, or you doing it manually. You got wonderful answers, this thread regarding, [How to Access Images (Application Resouces)](http://stackoverflow.com/a/9866659/1057230), might can help you further. – nIcE cOw Apr 22 '12 at 11:16

3 Answers3

5

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);
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
miqbal
  • 2,213
  • 3
  • 27
  • 35
3
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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
3

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.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • I'm still waiting to see that SSCCE, in order to determine if the layouts are also affecting the non-appearance of the image. +1 for both ideas. – Andrew Thompson Apr 22 '12 at 10:10
  • The odds are with you; but I have examined the entrails, and I'm going to stand/sit pat. :-) – trashgod Apr 22 '12 at 10:21
  • Well, haruspication has never let me down before, so my answer might be wrong. Be careful where you sit, those entrails get everywhere. :) – Andrew Thompson Apr 22 '12 at 10:36