我不知道为什么我的Java应用程序无法找到一张图片。

huangapple go评论65阅读模式
英文:

I don't know why my java application cannot find an image

问题

我在 src 文件夹中有我的图像,但当运行代码的这部分时,它不起作用。

Image img = Toolkit.getDefaultToolkit().getImage("background.png");

我认为问题与图像不在正确的目录有关,但我不知道应该把它放在哪里。我正在使用 IntelliJ,它没有向项目中添加图像的方法。

英文:

I have my image in the src folder, but when this part of the code is run it does not work.

Image img = Toolkit.getDefaultToolkit().getImage("background.png");

I think that the problem has to do with the image not being in the right directory, but I don't know where to put it. I am using IntelliJ and it does not have a way to add images to your project.

答案1

得分: 2

你可以直接在你的src文件夹中创建一个类,或者在你的包(package)中创建一个类,然后添加这段代码:

URL urlImage = YourClassName.class.getResource("yourimage.png");
Image image = ImageIO.read(urlImage);

如果你的目录结构是这样的:src/image 和 src/package/class
你可以使用 ../ 来返回上一级文件夹。例如,使用上面的目录结构,你的代码将如下所示:

URL urlImage = YourClassName.class.getResource("../yourimage.png");
Image image = ImageIO.read(urlImage);

更详细的解释是,在文件结构中,../ 表示返回上一级文件夹。希望这有所帮助!

英文:

You can make a class directly in your src folder, or in your package, and then add this code:

URL urlImage = YourClassName.class.getResource("yourimage.png");
Image image = ImageIO.read(urlImage);

If you have this structure: src/image and src/package/class
you can use ../ to go to the above folder. For example, using the structure above, your code will look like this:

URL urlImage = YourClassName.class.getResource("../yourimage.png");
Image image = ImageIO.read(urlImage);

For more explanation, in file structure ../ goes one folder above. I hope I helped!

huangapple
  • 本文由 发表于 2020年9月11日 22:37:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/63849219.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定