0

I have images i want to add in the following folder: G:\my java\DesktopApplication1\build\classes\desktopapplication1\resources.

How to go about adding image in this folder to my labels or frames?

Gabe
  • 84,912
  • 12
  • 139
  • 238
CyprUS
  • 4,159
  • 9
  • 48
  • 93

3 Answers3

2

Once built, the image will typically be inside a Jar. The resources in a Jar can be accessed a number of ways, here is one.

URL urlToImage = this.getClass().getResource(
    "/desktopapplication1/resources/the.png");
ImageIcon imageIcon = new ImageIcon(urlToImage);
JLabel ...
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
1

You can do something like this:

ImageIcon image = new ImageIcon("path_to_image");
JLabel label = new JLabel(image);
Heisenbug
  • 38,762
  • 28
  • 132
  • 190
0

I did something like this:

         JLabel l2=new JLabel("");
      try {
        Image img = ImageIO.read(getClass().getResource("resources/wait20.gif"));
        l2.setIcon(new ImageIcon(img));
          }
      catch (IOException ex) {
        }

It does work, but i would have liked it more had the GIF animation was displayed. Nevertheless, if a static image is to be displayed, this is the way to do it.

CyprUS
  • 4,159
  • 9
  • 48
  • 93
  • @sunandan "..but i would have liked it more had the GIF animation was displayed" What were you doing wrong? Animated GIFs appear just fine in JLabels here. BTW - tip: the word 'I' should *always* be upper case, no matter where it is in a sentence. – Andrew Thompson Mar 26 '11 at 18:30
  • @sunandan: if you were looking for animated gif solution try to have a look at this thread: http://stackoverflow.com/questions/149153/loading-animated-gif-from-jar-file-into-imageicon – Heisenbug Mar 26 '11 at 18:33
  • @overbose : I had a look at the thread . I have set ImageObserver property to l2, where my animated gif is added. However, no animation is displayed. – CyprUS Mar 26 '11 at 18:52
  • @sunandan re `catch (IOException ex) {}` That is very unhelpful when code breaks - go for something more like `catch (IOException ex) {ex.printStackTrace();}` – Andrew Thompson Mar 26 '11 at 18:53
  • @overbose : stranger still; if i set the path of the image ( copied from filesystem ) ; i get animation. – CyprUS Mar 26 '11 at 19:00
  • @sunandan: i don't understand what you mean. Are you trying with mine solution or with Andrew's? I never load an image like he told you, but he is sure more experienced than me so if my advice doesn't fit your needs, following his methods should be a better idea – Heisenbug Mar 26 '11 at 19:16