public void displayImage(String strfilename, JLabel JLlabel) {
try {
JLabel label = JLlabel;
String FileName = strfilename;
BufferedImage image = ImageIO.read(new File(FileName + ".jpg"));
if(image!=null){
ImageIcon icon = new ImageIcon(image);
label.setIcon(icon);}
else{
BufferedImage image2 = ImageIO.read(new File("NOIMAGE.jpg"));
ImageIcon icon2 = new ImageIcon(image2);
label.setIcon(icon2);
}
} catch (IOException ioe) {
}
}
나는 매우 감사하게 될 것입니다. try {} catch {}가 이미 있으므로 if {} else {} 루프가 필요 없습니다.
String FileName = file;
try {
BufferedImage image = ImageIO.read(new File(FileName + ".jpg"));
// Code for when the image is found
} catch (IOException ex) {
// Code for when the image is not found
}
편집 : @haraldK 지적 , 당신은 NullPointerException이가 발생 될 경우에는 존재하지만 읽을 수있는 파일을 가질 수 있습니다.
두 항목 모두 catch 절에서 처리 할 수 있습니다.
public void displayImage(String strfilename, JLabel label) {
try {
BufferedImage image = ImageIO.read(new File(strfilename + ".jpg"));
ImageIcon icon = new ImageIcon(image); // Can throw NullPointerException if the file is found but is unreadable
label.setIcon(icon);
} catch (IOException | NullPointerException ex) {
ImageIcon icon = new ImageIcon("NOIMAGE.jpg");
label.setIcon(icon);
}
// You're probably going to have to pack or validate your container here
}
주목할 가치가있는 점 중 하나는 NOIMAGE에 대한 예외를 확인하지 않는다는 것입니다. 추가해야 할 수도 있습니다.
File.exists()는 파일이 있지만 읽을 수없는 파일 (텍스트 파일 및 기타 파일)을 처리하기 때문에 File.exists()를 호출하는 것보다 낫습니다.
파일을 읽을 수 없거나 존재하지 않으면'ImageIO.read'는'IOException'을 던집니다. 개인적으로, 예를 들어,'ImageIO.read'에 의존하여'File # exists'를 사용합니다. – MadProgrammer