使用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)
我究竟做错了什么?
收到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;
}
}
使用此方法的好处在于,它是一种实用工具,可以在需要添加图标的情况下多次使用,它的优点是,如果图像不能位于指定的路径,它还会显示错误。
我强烈怀疑这与您提供的路径有关。最好查看文件夹结构。尝试将路径作为“ project / print.gif”传递
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句