我试图在同一窗口中加载多个图像,这样可以防止大量的复制和粘贴,我做了名为badgeIMG图像类,如下所示:
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,我有这样的代码:
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);
问题是,我得到一个NullPointerException异常,宣布从上面的代码badgePath的时候,但是当我把与真实文件路径的一个替代badgePath,它并没有给我的错误,但我希望能够在一个字符串插头文件路径,并使其显示多个图像。 有任何想法吗?
以下是错误:
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)