英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论