我正在为我的课程设计一个项目,并被要求在系统中显示产品的相关图像,用户可以添加产品,并在此过程中输入图像文件的名称。然后,程序将找到图像文件并显示其产品信息。
我想添加一些其他代码,以便在没有与字符串输入匹配的图像文件时,显示标准图像。我到目前为止的代码要么显示图像文件(如果找到),要么不显示任何内容。有人可以告诉我如何修改它,以便在找不到关联的图像文件的情况下可以显示标准图像。标准图片就是“ no-image-found.jpg”。这是代码:
public void showImage(JLabel imageArea, String image){
BufferedImage img = null;
try {
img = (BufferedImage)ImageIO.read(new File(image));
Image actualimage = img.getScaledInstance(imageArea.getWidth(), imageArea.getHeight(), 0);
imageArea.setIcon(new ImageIcon(actualimage));
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
非常感谢任何帮助,如果这是一个菜鸟问题,我诚挚的歉意,我对Java还是陌生的。
在捕获中,您可以加载标准图像并显示它
[假设路径有效,则基本检查图像是否存在,否则获取标准图像。您可以有类似的内容:
public void showImage(JLabel imageArea, String image)
{
BufferedImage img = null;
try
{
file = new File(image);
if (file.exists())
{
img = ImageIO.read(file);
}
else
{
file = new File(standardImagePath);
img = ImageIO.read(file);
}
Image actualimage = img.getScaledInstance(imageArea.getWidth(), imageArea.getHeight(), 0);
imageArea.setIcon(new ImageIcon(actualimage));
}
catch (IOException e)
{
System.out.println(e.getMessage());
}