我正在尝试使用以下代码导入一些照片。看起来我刚刚添加的检查(如果声明),回复为“yay”,所以文件就在那里。所以它可以找到文件工作正常,但由于某种原因它无法导入文件并创建imageIcon。任何帮助将不胜感激!我也试过相对路径,但没有成功!
任何帮助都会非常感激,因为我已经把头发拉了很长时间了!
public class Photos {
ImageIcon bi = new ImageIcon();
// Position
private int x, y;
// Diameter (storlek)
private int diameter;
private int dynamicdiameter;
public void importPhoto(String name) {
String path = "/Users/Cedric/Dropbox/UU/OOPJ/Foton/src/img/";
File imageCheck = new File(path+name);
if(imageCheck.exists()){
System.out.println("yay");
}
else{System.out.println("noo");}
ImageIcon bi = createImageIcon(path+name, "Photo");
}
protected ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
}
一些细微的变化应该是正确的。看评论 :
public void importPhoto(String name) {
String path = "/img/" + name; //use correct path
URL imgURL = getClass().getResource(path);
if(imgURL != null){
System.out.println("yay");
bi = createImageIcon(imgURL, "Photo"); //avoid declaring a new bi
} else {
System.err.println("noo");
}
}
protected ImageIcon createImageIcon(URL imgURL,String description) {
return new ImageIcon(imgURL, description);
}