从URL获取图像返回NullPointerException(Java)
我正在尝试使用从URL获取的图像设置JButton ImageIcon。这是我的代码:从URL获取图像返回NullPointerException(Java),java,image,url,nullpointerexception,javax.imageio,Java,Image,Url,Nullpointerexception,Javax.imageio,我正在尝试使用从URL获取的图像设置JButton ImageIcon。这是我的代码: try{ URL imageFile=new URL(picturePath); carPic=ImageIO.read(imageFile); picturePane.setIcon(new ImageIcon(carPic));//this line gives the exception }catch
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();
}
其中“picturePath”是图像URL
我计划使用的URL只是通过“复制图像地址”获得的普通URL,并读取如下内容:
我必须对URL做些什么才能让它们正常工作,还是代码本身存在其他问题 我已经找到了解决您的问题的方法,我想它可能会有所帮助:)
由于URL内容无效,
ImageIO
生成NullPointerException
是不寻常的-如果它无法读取URL,通常会抛出某种类型的IOException
-我怀疑picturePath
或picturePane
实际上是null
相反-哪一行生成了NPE?您使用指定URL读取图像的代码工作正常-我怀疑您的问题出在其他地方请添加记录的错误消息和堆栈跟踪,以帮助其他用户了解问题可能出在何处。@MadProgrammer Post经过编辑以更好地显示生成NPE的内容picturePath
是一个字符串,我事先放了一行打印出来,效果很好,所以我知道它不是空的。我刚刚在picturePane
上运行了一个测试,它确实返回null,所以我将尝试修复它。谢谢你,多亏了你,我才让它工作起来!