在NetBeans中将ImageIcon添加到jbutton时出现空指针异常

时间:2012-10-31 05:51:59

标签: java swing jbutton imageicon

使用NetBeans将ImageIcon添加到按钮属性。

    print.setFont(new java.awt.Font("Serif", 0, 14)); 
    print.setIcon(new javax.swing.ImageIcon(getClass().getResource("/project/print.gif"))); 
    print.setMnemonic('P');
    print.setText("Print");
    print.setToolTipText("Print");

编译时显示

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(ImageIcon.java:205)
    at project.Editor.initComponents(Editor.java:296)

我做错了什么?

4 个答案:

答案 0 :(得分:6)

您获得NullPointerException的原因是由于某种原因无法找到您尝试指定的图像文件。因此getResource()方法返回null。

首先,您可以阅读有关在此链接中添加图标的信息:"How to Use Icons"

他们建议的方法之一是创建方法:

/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path,
                                           String description) {
    java.net.URL imgURL = getClass().getResource(path);
    if (imgURL != null) {
        return new ImageIcon(imgURL, description);
    } else {
        System.err.println("Couldn't find file: " + path);
        return null;
    }
}

使用此方法的优势,除了可以在您想要添加图标时多次使用的实用程序方法之外,它还会显示错误,以防图像显示不在指定的路径上。

我强烈怀疑这与您提供的路径有关。看一下文件夹结构会很好。尝试将路径传递为“project / print.gif”

答案 1 :(得分:1)

解决方案: 您需要在资源中添加图像文件夹 结构是这样的 src/main/resources/Images/youricon.jpg Check this image

答案 2 :(得分:0)

表达式<fileSet filtered="true" encoding="UTF-8"> <directory></directory> <includes> <include>**/log4j.properties</include> </includes> </fileSet> 调用方法getClass(间接从Object类继承)以检索对表示“Editor class”(您的类)声明的Class对象的引用。然后,该引用用于调用Class方法getResource,该方法将图像的位置作为URL返回。 ImageIcon构造函数使用URL来定位图像,然后将其加载到内存中。 JVM使用类加载器将类声明加载到内存中。类加载器知道它加载的每个类在磁盘上的位置。方法getResource使用Class对象的类加载器来确定资源的位置,例如图像文件。因此,您将获得NullPointerException,并且图像文件必须存储在与“Editor.class”文件相同的位置。您尝试在此处使用的技术使应用程序能够从相对于类文件位置的位置加载图像文件

因此,您应该将“print.gif”文件移动到“/ projectName / bin / packageName”文件夹并尝试

getClass().getResource("/project/print.gif")

而不是

print.setIcon(new javax.swing.ImageIcon(getClass().getResource("print.gif")));

答案 3 :(得分:0)

这是由于图像文件不在指定目录中的原因。您可能以某种方式输入了错误的名称或更改了名称。