0

I'm trying to set JButton ImageIcon with an image taken from a URL. This is the code I have:

        try{
            URL imageFile=new URL(picturePath);
            carPic=ImageIO.read(imageFile);
            picturePane.setIcon(new ImageIcon(carPic));//this line gives the exception
        }catch(IOException e){
            e.printStackTrace();
        }

Where "picturePath" is the image URL.

The URLs I plan to use are just the normal ones obtained with "copy image address" and read as such: "https://www.topgear.com/sites/default/files/544822_0.jpg"

Do I have to do something to the URLs to get them to work right, or is there some other problem with the code itself?

halfer
  • 19,824
  • 17
  • 99
  • 186
Snikle
  • 1
  • 1
  • It would be unusual for `ImageIO` to generate a `NullPointerException` because the URL content was invalid - it would generally throw a `IOException` of some kind instead if it failed to read the URL - my suspicion is that either the `picturePath` or `picturePane` are actually `null` instead - which line generates the NPE? – MadProgrammer Mar 05 '20 at 21:39
  • Your code to read the image, using the specified URL, works just fine - I suspect you issue is somewhere else – MadProgrammer Mar 05 '20 at 21:42
  • Please add the logged error message and stack trace to help other users to understand where the problem might be. – andy Mar 05 '20 at 21:43
  • @MadProgrammer Post is edited to better show what generates the NPE. `picturePath` is a String and I put a line to print it beforehand and that works fine, so I know it's not null. I just ran a test on `picturePane` and it does return null, so I'll try to fix that. Thank you. – Snikle Mar 05 '20 at 21:53
  • @MadProgrammer I got it to work thanks to you! – Snikle Mar 05 '20 at 22:00

1 Answers1

0

I have found this solution with the problem you have, I think it might help :) Getting image from url

Manuel Miranda
  • 105
  • 1
  • 1
  • 7