声明新的ImageIcon时为nullpointerexception [英] nullpointerexception when declaring new ImageIcon
问题描述
我试图在同一窗口上加载多个图像,因此为了防止大量复制和粘贴,我制作了一个名为badgeIMG的图像类,如下所示:
I am trying to load multiple images on the same window, so to prevent a lot of copy and paste, I made an image class called badgeIMG that looks like this:
package BattleSim;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class badgeIMG extends JPanel{
Image badgeIcon;
String badgePath;
int x = 0;
int y = 0;
public badgeIMG() {
ImageIcon ii = new ImageIcon(this.getClass().getClassLoader().getResource(badgePath));
badgeIcon = ii.getImage();
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(badgeIcon, x, y, null);
}
}
然后在另一个名为badgeSelectionWindow的类中,我有这段代码:
Then in another class, called badgeSelectionWindow, I have this piece of code:
badgeIMG allOrNothingBadge = new badgeIMG();
badgeIMG closeCall = new badgeIMG();
allOrNothingBadge.badgePath = "/Badges/allornothing.gif";
allOrNothingBadge.x = 128;
allOrNothingBadge.y = 144;
closeCall.badgePath = "/Badges/closecall.gif";
closeCall.x = 256;
closeCall.y = 144;
add(allOrNothingBadge);
add(closeCall);
问题是,当从上述代码中声明badgePath时,我得到了NullPointerException,但是当我用实际文件路径之一替换了badgePath时,它没有给我错误,但是我希望能够插入一个带有文件路径的字符串,并使其显示多个图像.有什么想法吗?
The problem is, I get a NullPointerException when declaring a badgePath from the above code, but when I put replace badgePath with one of the real file paths, it does not give me error, but I want to be able to plug in a String with the file path and have it display multiple images. Any ideas?
这是错误:
Exception in thread "main" java.lang.NullPointerException
at sun.misc.MetaIndex.mayContain(Unknown Source)
at sun.misc.URLClassPath$JarLoader.getResource(Unknown Source)
at sun.misc.URLClassPath.getResource(Unknown Source)
at sun.misc.URLClassPath.getResource(Unknown Source)
at java.lang.ClassLoader.getBootstrapResource(Unknown Source)
at java.lang.ClassLoader.getResource(Unknown Source)
at java.lang.ClassLoader.getResource(Unknown Source)
at BattleSim.badgeIMG.<init>(badgeIMG.java:17)
at BattleSim.badgeSelectionWindow.<init>(badgeSelectionWindow.java:11)
at BattleSim.badgeSelectionWindow.main(badgeSelectionWindow.java:36)
推荐答案
您的badgePath
是null
.
构造函数将badgePath
用作ImageIcon
构造函数的参数,但并未首先对其进行初始化.使用这样的构造函数:
The constructor uses the badgePath
as argument for the ImageIcon
constructor, but it didn't initialize it first. Use a constructor like this:
public badgeIMG(String path)
{
ImageIcon ii = new ImageIcon(this.getClass().getClassLoader().getResource(path));
badgeIcon = ii.getImage();
badgePath = path;
}
注意:非常重要:Java命名约定是类以大写字符开头.因此,将类名和文件名更改为:BadgeImg
或BadgeIMG
.
Note: Very important: Java naming conventions are that classes start with an uppercase char. So change the class name and file name to: BadgeImg
or BadgeIMG
.
这篇关于声明新的ImageIcon时为nullpointerexception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!