为什么 Java ImageIcon 没有进入 catch 子句?
Why Java ImageIcon isn't enter catch clause?
当我尝试创建 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;
}
但是即使出现错误,也不是跳入catch状态。为什么 ?
如果您查看堆栈跟踪,您会注意到其中列出了 none 个函数。抛出异常的线程与运行代码的线程不同;它是一个负责为 ImageIcons 异步加载图像的线程,因此您无法捕获该异常
如果加载 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();
}
当我尝试创建 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;
}
但是即使出现错误,也不是跳入catch状态。为什么 ?
如果您查看堆栈跟踪,您会注意到其中列出了 none 个函数。抛出异常的线程与运行代码的线程不同;它是一个负责为 ImageIcons 异步加载图像的线程,因此您无法捕获该异常
如果加载 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();
}