2012-12-03 60 views
0

我一直在将我的Java应用程序的所有图像放入src中的一个名为“rtype”的包中,我也有我的Class来处理这些图像。我想对图像进行排序并将它们放在自己的文件夹中。当我这样做时,图像将不再加载到类中,并且我知道这是因为我更改了文件路径。我已经做了一些研究并尝试了一些不同的东西。这基本上是我原来的:在Java应用程序中更改文件的位置

String walkingDown = "WalkingDown.gif"; 
ImageIcon ii; 
Image image; 
ii = new ImageIcon(this.getClass().getResource(walkingDown)); 
image = ii.getImage(); 

它工作得很好,然后我把图像的位置移动到类的位置以外。现在它不能找到图像。下面是我尝试过,并在网上找到的尝试(该文件夹的名称是精灵):

//use getClassLoader() inbetween to find out where exactly the file is 
ii = new ImageIcon(this.getClass().getClassLoader().getResource(standingDown)); 

//Changing the path 
String walkingDown = "src\\Sprites\\WalkingDown.gif"; 
//also tried a variation of other paths with no luck 

我使用的是C盘,但不希望使用“C”在我的扩展中,因为我希望它可以访问,无论我把项目放在哪里。我在这一点上相当坚持,并且已经做了足够的研究,意识到现在是时候提问了。

+0

什么操作系统您使用的? – sdasdadas

+0

这里有很多关于这个的问题,例如[this one](http://stackoverflow.com/q/2343187/18573) –

+0

我现在正在使用Windows 7。 –

回答

1

我有一个与该名称图像的单独的“包”(src文件夹中)

尝试是这样的:

try { 
     ClassLoader cl = this.getClass().getClassLoader(); 
     ImageIcon img = new ImageIcon(cl.getResource("images/WalkingDown.gif")); 
    } 
    catch(Exception imageOops) { 
     System.out.println("Could not load program icon."); 
     System.out.println(imageOops); 
    } 
+0

现在会尝试 –

+1

请注意,正斜杠/不管操作系统如何工作(相当于windows的反斜杠) – Thorn

+0

太棒了!谢谢你,先生。 –

1

您的变量名为walkingDown,但您将standingDown传递给getResource()方法。

+0

很好的捕获,它不像我的程序中,但我现在将编辑 –

1
new ImageIcon("src/Sprites/WalkingDown.gif"); 
+0

好吧,这个作品。但是,你能告诉我使用这个和使用classLoader的区别是什么? –

+1

这段代码正在寻找一个相对于执行代码的特定路径的文件。如果你构建你的项目然后运行jar,上面的代码将无法工作,除非它们是与jar文件位于同一路径中的src目录。我发布的方法假设图像文件已被打包到jar文件中,因此在分发应用程序时,您希望使用类加载器,以便可以将所有文件一起分发到一个jar中。 – Thorn

+0

@Thorn现在有道理,谢谢。 –

相关问题