1

我对 eclipse 上的相对文件路径有一个烦人的问题。我已经看过很多关于如何修复它的帖子,但对我没有任何帮助。

我的目录结构如下:

在此处输入图像描述

C.java II里面要指明NotSet_16x16.png的相对路径

 ip_address_image_label.setIcon (new ImageIcon ("<relativePath>\\NotSet_16x16.png"));
4

4 回答 4

3

Don't keep resources with the code. Create a separate 'resources' folder (a source folder along with the src you already have), an images folder in it, and keep those PNGs there. Do the same for the rest of your resources (I see you have a csv and a txt file).

When done with that, you will see that you shouldn't access your resources having in mind the location of the class where you need them, but only having in mind that they are resources and all of them are at the same place, i.e. get them with an absolute path like /images/NotSet_16x16.png. So in your class you could do something like:

new ImageIcon(this.getClass().getResource("/images/NotSet_16x16.png"))
于 2013-10-15T23:46:59.120 回答
1

通常,代码中的文件用作资源。编译后,它们最终得到类文件,最后在一个.jar文件中。

因此,将类中的数据作为资源读取到 abyte[]中,并使用构造函数创建图像。CImageIcon(byte[])


或者,您可以使用可以通过使用资源的 URL创建图标来读取的中间图像。这可能更简洁,因为您不必费心将 an 读入缓冲区。InputStreambyte[]


请注意,如果您使用其中任何一种方法(因为类文件和图像在同一个包中),您可以直接使用文件名。您无需指定路径。

于 2013-10-15T23:30:21.647 回答
1

试试这个:

String filePath = ".\\images\\NotSet_16x16.png";

其中 «.\» 是 Eclipse 项目的根目录,«images» 是 Eclipse 项目中包含用户文件的文件夹。由于我们谈论的是 Windows 操作系统,所以我们必须使用«\» 而不是 «/»,就像在 Linux 中一样,但«\» 是保留符号,因此我们必须输入 «\» 才能获得所需的结果。

于 2014-06-10T21:44:50.363 回答
0

我为我的问题尝试了所有这些答案,但都没有奏效。我问了一个朋友,他完美地回答了我的问题。创建一个名为 Images 的源文件夹(即,如果您使用的是 eclipse,请右键单击您的项目 -> 新建 ->sourceFolder)。随便你怎么称呼它,我叫我的图像。在里面放一些图片。

现在我有了 JLabels,我给了他们 ImageIcons。看下面的代码。

    ImageIcon BPawn;
    ImageIcon WPawn;
    JLabel Label = new JLabel[8][8] //2D array of labels that gives each spot a position.
    public void setPieces(){
        //set up pawns in their respective positions.
        BPawn = new ImageIcon("Images/BPawn.png", "BPawn");
        WPawn = new ImageIcon("Images/WPawn.png", "WPawn");
    for(int i=0;i<Label[0].length;i++){
        Label[1][i].setIcon(BPawn);
        Label[6][i].setIcon(WPawn);
    }//end for

    }//end setPieces.

setPieces() 方法中还有更多内容,但这一瞥是当您创建可执行 jar 并希望显示图像时如何引用源文件夹中的图像。

于 2015-05-01T03:13:49.017 回答