gpt4 book ai didi

java - 如何在我的应用程序中存储图像而无需提供图像的确切目录?

转载 作者:行者123 更新时间:2023-12-02 04:47:50 25 4
gpt4 key购买 nike

目前,我正在尝试为我的应用程序获取背景图像,并且我必须在代码中指定图像的确切位置,如下所示

// Add image to the background
try {
setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("/Users/Dropbox/Team Project/AutoRepair/AutoRepairSystem/src/res/bg_login2.png")))));
} catch (IOException e) {
System.out.print("Image did not load!");
}

我将图像存储在我的 res 文件夹中,但每次在另一台计算机上运行代码时,我仍然必须更改前 2-3 个文件夹名称。

考虑到我必须查看大约 20 个 java 文件和大约 20 个图像,这确实令人沮丧。

最佳答案

将图像放入项目的包中。这样,图像就可以随项目一起移动,或者打包到 jar 文件中。要以这种方式访问​​资源,可以使用 Class 的 getResource() 或 getResourceAsStream() 方法:

URL urlToResource = MyClass.class.getResource("/path/to/image");//alternative, you can use the getClass() method of object
ImageIcon icon = new ImageIcon(urlToResource);

请注意,路径取决于您放置文件的位置。您可以使用绝对路径(前面带有“/”)或相对路径(相对于调用类的位置)。

关于java - 如何在我的应用程序中存储图像而无需提供图像的确切目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29520837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com