当我尝试创建ImageIcon时,我收到此错误:
sun.awt.image.ImageFormatException: Unsupported color conversion request
at sun.awt.image.JPEGImageDecoder.readImage(Native Method)
at sun.awt.image.JPEGImageDecoder.produceImage(Unknown Source)
at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
at sun.awt.image.ImageFetcher.run(Unknown Source)
如果发生这个错误,那么我想加载另一个图像,所以我使用了try-catch:
public Component getListCellRendererComponent(
JList<?> list, Object value, int index,
boolean isSelected, boolean cellHasFocus )
{
// Display the text for this item
setText(value.toString());
// Pre-load the graphics images to save time
String iconurl=ABC.getCiconUrl();
if(iconurl.isEmpty())
{
iconurl="img\\backgroundpic.png";
}
try {
image = new ImageIcon(iconurl);
} catch (Exception e) {
image = new ImageIcon("img\\backgroundpic.png");
}
// Set the correct image
setIcon( image );
return this;
}
但即使出现错误,它也不会跳入捕获状态。为什么?
答案 0 :(得分:2)
如果查看堆栈跟踪,您会注意到其中没有列出任何功能。抛出异常的线程与运行代码的线程不同;它是一个负责为ImageIcons异步加载图像的线程,因此你无法捕获该异常
答案 1 :(得分:0)
如果你加载一个 ImageIO 图像,你将不得不像这样捕获 IO 异常:
try {
// The image file is in the java source project \workspace\myproject
img = ImageIO.read(new File("image.png"));
} catch (IOException e) {
e.printStackTrace();
}
使用 ImageIcon,您可以使用异常对象捕获异常。然后您可以使用 getResource(path)
加载图像。我这样试过,效果很好:
try {
ImageIcon img = new ImageIcon(getClass().getClassLoader().getResource("image.png"));
} catch (Exception e) {
e.printStackTrace();
}