gpt4 book ai didi

java - 需要 NullPointEreexception 错误帮助

转载 作者:行者123 更新时间:2023-12-03 07:41:28 26 4
gpt4 key购买 nike

我想将图标应用于我的程序,但它给了我一个错误。看起来一切都很好,这就是为什么我不知道它有什么问题。

public static ImageIcon createIcon (String path) {
URL url = System.class.getResource(path);

if(url == null) {
System.err.println("Unable to load image: " + path);
}

ImageIcon icon = new ImageIcon(url); //here is line 30 in class Utils

return icon;
}

他的错误是:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.desktop/javax.swing.ImageIcon.<init>(ImageIcon.java:217)
at gui.Utils.createIcon(Utils.java:30)

最佳答案

问题是urlnull .检查构造函数是如何实现的:

public ImageIcon (URL location) {
this(location, location.toExternalForm());
}

locationnull , location.toExternalForm()会抛出 NullPointerException .

事实上,如果 pathnull ,这也可能导致 NullPointerException .看看如何 getResource已实现。
public URL getResource(String name) {
name = resolveName(name);
//...
}

private String resolveName(String name) {
if (!name.startsWith("/")) {
Class<?> c = this;
while (c.isArray()) {
c = c.getComponentType();
}
String baseName = c.getPackageName();
if (baseName != null && !baseName.isEmpty()) {
name = baseName.replace('.', '/') + "/" + name;
}
} else {
name = name.substring(1);
}
return name;
}

如您所见,如果 namenull , name.startsWith("/")会抛出 NullPointerException .

请按以下步骤操作:
public static ImageIcon createIcon (String path) {
if(path == null) {
System.err.println("Path is null");
return null;
}

URL url = System.class.getResource(path);
ImageIcon icon = null;

if(url != null) {
icon = new ImageIcon(url);
} else {
System.err.println("Unable to load image: " + path);
}

return icon;
}

关于java - 需要 NullPointEreexception 错误帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60908243/

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