gpt4 book ai didi

java - ProblemWithTheJar .jar - 图像不显示

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

问题如下 - 我正在用 java 编写 Eclipse 程序..生成的文件夹结构是主项目文件夹: Animal Classification/内部: bin/、 images/、 pics/bin/文件夹中: users/metropolia/allClasses.class

程序正常启动并工作 -> 图像位于 images/和 pics/文件夹中 -> 它们由 users.metropolia.Hieararchy 使用

但是,当我通过 Eclipse 或通过 CMD.exe 在与源文件夹不同的文件夹中创建 .jar 时,该 jar 不会显示图像,即使它们打包在其中。在 Hierarchy.class 中,图像的路径是(“images/name.jpg”或“pics/name.jpg”)。

然后我尝试使用 ClassLoader.getSystemResource("images/name.jpg") - 但现在 eclipse 和 cmd.exe 发出警告并且不启动程序 -> 线程 main 中的 NullPointerException = 行中的错误ClassLoader静态使用...

我真的很感激任何帮助

更新:

http://users.metropolia.fi/~artemm/

请从那里下载代码它可以作为 SFX 存档下载,或者如果您担心病毒,只需下载普通的 RAR 存档

非常感谢您的帮助

主类位于users/metropolia/Program.java

更新 2:

@MockerTim

非常感谢您的帮助 - 现在一切正常。此外,我设法找到了另一个障碍 - 它没有调用图像,因为调用是:“Fish.jpg”而图片是:“fish.jpg” - 难怪它找不到任何东西并给出错误。

再次非常感谢您,真的很感激!

最佳答案

您使用的路径不正确。

您应该在代码中使用以下路径:分别是 ../../images/name.jpg../../pics/name.jgp

Nate提到过,您可以以“/”开始路径,并分别使用 /images/name.jpg/pics/name.jpg

当您在 users.metropolia.Hieararchy 类中使用 images/name.jpg 路径时,您的代码会尝试查找文件 name.jpg > 在users/metropolia/images文件夹中。当然,它失败了。

参见Locating resources in Java了解详情。

这是一个简单的例子:

package users.metropolia;

import java.net.URL;
import javax.swing.ImageIcon;

public class IconManager {
/** Returns an ImageIcon, or null if the path was invalid. */
public static ImageIcon loadImageIcon(String path) {
URL imgURL = IconManager.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}

public static void main(String[] args) {
// Using absolute (to jar) paths
ImageIcon icon3 = loadImageIcon("/pics/spider.jpg");
ImageIcon icon4 = loadImageIcon("/imagess/ant.jpg");
}
}

更新:

我已经下载了您的代码(来自 your link ),并添加了上面的 IconManager 类,并使用其 loadImageIcon() 方法来初始化您的 anImages 数组和 MyDrawPanel 类。现在你的程序看起来像这样:

enter image description here

我对您的代码所做的更改:

在类层次结构中:

for (int i = 0; i < options.length; i++) {
//anImages[i] = new ImageIcon("/images/" + options[i] + ".jpg");
anImages[i] = IconManager.loadImageIcon("/images/" + options[i] + ".jpg");
listObj[i] = new RendObject(options[i], anImages[i]);
}

在类MyDrawPanel中:

public MyDrawPanel(String x) {
//picture = new ImageIcon(x).getImage();
picture = IconManager.loadImageIcon(x).getImage();
}

当然,我在需要的地方从 JComboBox 中删除了“generic”。

备注:要使您的程序显示选定的图像而不是蜘蛛图像,您应该进一步修改您的程序。

关于java - ProblemWithTheJar .jar - 图像不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7835991/

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