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

Ven*_*ava 8 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");
Run Code Online (Sandbox Code Playgroud)

编译时显示

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

我究竟做错了什么?

Suj*_*jay 6

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

首先,您可以阅读有关在此链接中添加图标的信息:"如何使用图标"

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

/** 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

除了是一种可以在想要添加图标时多次使用的实用方法之外,使用此方法的优点是,如果图像无法位于指定的路径,它还会向您显示错误.

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