Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在我的应用程序中存储图像而不必给出图像的确切目录?_Java_Image_File_Directory - Fatal编程技术网

Java 如何在我的应用程序中存储图像而不必给出图像的确切目录?

Java 如何在我的应用程序中存储图像而不必给出图像的确切目录?,java,image,file,directory,Java,Image,File,Directory,目前,我正在尝试为我的应用程序获取背景图像,我必须在代码中指定图像的确切位置,如下所示 // 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"))))); } cat

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

// 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文件中。要以这种方式访问资源,可以使用类的getResource()或getResourceAsStream()方法:

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

注意:路径取决于放置文件的位置。您可以使用绝对路径(以“/”开头)或相对路径(相对于调用类的位置)

这就是Class.getResourceAsStream()和相关方法的用途——将图像存储在与给定类相同的位置,然后可以使用该类定位图像。这样,图像就可以保存在JAR文件中,代码仍然可以正常运行。查阅有关如何使用此工具的教程,这样您就不必更改其他机器的代码。

好的,所以我所做的是在我的项目中创建另一个源文件夹,并将其命名为“img”,然后将我的图像放入其中。因此,现在我不必像以前那样键入整个目录,只需输入/img/bg_login2.png,效果非常好

try {

        setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("img/bg_login2.png")))));
    } catch (IOException e) {
        System.out.print("Image did not load!");
    }