1

When I try to create a JLabel, it displays text perfectly and is placed fine within the container, but if I try to add an image to the label, nothing shows up.

ImageIcon icon = new ImageIcon("../media/link_walk.png", "hh");
JLabel j = new JLabel("hello");
j.setIcon(icon);
p.add(j);
Sasha McCarn
  • 41
  • 1
  • 4

2 Answers2

3

If your app. is in Jar files and the image is an application resource, it will also be in a Jar file.

The ImageIcon constructor that accepts a String presumes the String represents a file path/name. A File object cannot be established to a resource in a Jar. For resources in a Jar, it is necessary to access them by URL.

To get an URL to something in a Jar, use something like..

URL urlToImage = this.getClass().getResource("/media/link_walk.png");
// Check the URL!
System.out.println("urlToImage is " + urlToImage);

Then use the ImageIcon constructor that accepts an URL.

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

JLabels are not opaque by default, and so background color changes won't be seen unless you make them opaque via setOpaque(true). Also the preferredSize of the JLabel will depend on the text it holds.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373