ImageIcon找不到照片,路径正确

时间:2019-03-23 16:56:34

标签: java swing resources imageicon

我正在尝试使用以下代码导入一些照片。好像我刚刚添加的支票(if语句)一样,返回为“是”,因此文件在那里。因此它可以找到文件,但工作正常,但是由于某种原因,它无法导入文件并创建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;
        }
    }    
}

1 个答案:

答案 0 :(得分:0)

一些较小的更改应该使它正确。查看评论:

    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);
    }