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?

5
  • 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? Commented Mar 5, 2020 at 21:39
  • Your code to read the image, using the specified URL, works just fine - I suspect you issue is somewhere else Commented Mar 5, 2020 at 21:42
  • Please add the logged error message and stack trace to help other users to understand where the problem might be. Commented Mar 5, 2020 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. Commented Mar 5, 2020 at 21:53
  • @MadProgrammer I got it to work thanks to you! Commented Mar 5, 2020 at 22:00

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.