我的代码放在project这个package下,使用
ImageIcon topIcon = new ImageIcon(this.getClass().getResource("../images/test.jpg"));
这个方法找到图片。目录结构为/work/bin/project/[all .class files]
         /images/test.jpg
     /src/project/[all .java files]现在这个方法是可行的。但是我想把images目录直接放在/work文件夹下,然后用以下方法
ImageIcon topIcon = new ImageIcon(this.getClass().getResource("../../images/test.jpg"));
这个就行不通,为什么呢?谢谢

解决方案 »

  1.   


    ImageIcon topIcon = new ImageIcon(this.getClass().getResource("../../images/test.jpg"));
    试了一下,两次返回上级目录就找不到资源了,听听楼下怎么说//你要改路径的话可以通过回避Class.getResource();来解决
    //用Image获得图片转成ImageIcon
    String directory = System.getProperty("user.dir");
    //directory是你的package所在目录,这里就是project所在目录了,注意这是在非IDE环境下
    //如果在eclipse中,这个directory就是你的工程的路径
    directory += "\\images\\test.jpg";  //假设 ProjectName/images/test.jpg
    Image img = Toolkit.getDefaultToolkit().getImage(directory);
    background = new ImageIcon(img); 
      

  2.   

    我的怎么可以啊 你写成
    ImageIcon topIcon = new ImageIcon(this.getClass().getResource("../works/images/test.jpg"));
      

  3.   

    总是不行,好像程序默认路径必须在所有class文件所在目录,而且不能返回两层