且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

加载图像时,枚举抛出错误

更新时间:2022-12-06 18:53:48

您的枚举无法正确初始化,很可能是因为它在构造函数中引发了 NullPointerException

Your enum cannot be correctly initialized, most likely because it throws a NullPointerException in the constructor.

ImageIcon i = new ImageIcon(this.getClass().getResource("img/" + imagepath));

使用上面的语句,您正在寻找 img / imagepath 枚举放在同一软件包中。使用 / 前缀路径

With the above statement, you are looking for img/imagepath in the same package as your enum. Prefix the path with / instead

ImageIcon i = new ImageIcon(this.getClass().getResource("/img/" + imagepath));

使它相对于类路径的根,因为我假设您的文件( img 包)。

so that it is relative to the root of the classpath, as I assume your file (img package) is.

如果 / img 只是一个文件夹,您需要将其添加到您的类路径中。如果您使用的是Eclipse,请将其拖放到 src 文件夹中。

If /img is just a folder, you need to add it to your classpath. Drag and drop it into the src folder if you are on Eclipse.