0

I'm trying to make an application to manage some drink recipes... I need to show the drink image in a JPanel already working with the file path like this:

ImageIcon image = new ImageIcon("src/fotos/trinidad.jpg");

The problem is that when I try to set this path setting it with the object name, the image is not being loaded.

String s = ("src/fotos/"+b.getNome().toLowerCase()+".jpg");
ImageIcon image = new ImageIcon(s);

Printing this string s I have this result:

System.out.println(s);

src/fotos/trinidad.jpg

Apparently it looks the same path, but the image is not being loaded. What am I doing wrong?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Yoostah
  • 5
  • 2
  • 5
    `src` folder does not exist when your code is compiled and ran, by the way. Please see https://stackoverflow.com/questions/1464291/how-to-really-read-text-file-from-classpath-in-java – OneCricketeer May 24 '17 at 02:13
  • 2
    `ImageIcon image = new ImageIcon(getClass().getResource("/fotos/trinidad.jpg"));` would generate a more reasonable result, but I'd be tempted to using `ImageIO.read` instead, as it throws a `IOException` if the image can't be read – MadProgrammer May 24 '17 at 02:16
  • 3
    To add to the comment of @cricket_007. Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An [tag:embedded-resource] must be accessed by URL rather than file. See the [info. page for embedded resource](http://stackoverflow.com/tags/embedded-resource/info) for how to form the URL. – Andrew Thompson May 24 '17 at 02:16
  • I tried with @MadProgrammer sugestion and kinda fixed my code. The thing is that it was not the problem causing my application to not load the image correctly. I had to add the drinks again to solve the problem. Thx for the fast answer and for teaching me about embedded resoruce. – Yoostah May 24 '17 at 03:41

1 Answers1

0

Try something like this, if the image (path) does not exist you can catch the exception and treat accordingly.

    BufferedImage drinkImage = null;
    try {
        drinkImage= ImageIO.read(new File("src/fotos/trinidad.jpg"));
    } catch (IOException e) {
        // TODO
        e.printStackTrace();
    }
    ImageIcon image = new ImageIcon(drinkImage);

    // Put image in your JPanel
S. Esteves
  • 415
  • 4
  • 14
  • You solution is as good as @MadProgrammer one. I'm currently using `ImageIcon image = new ImageIcon(getClass().getResource("/fotos/trinidad.jpg"));` – Yoostah Jun 29 '17 at 16:07