我试图在同一窗口上加载多个图像,因此为了防止大量复制和粘贴,我制作了一个名为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);


问题是,当从上述代码中声明badgePath时,我得到了NullPointerException,但是当我用实际文件路径之一替换了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)

最佳答案

您的badgePathnull

构造函数将badgePath用作ImageIcon构造函数的参数,但并未首先对其进行初始化。使用这样的构造函数:

public badgeIMG(String path)
{
    ImageIcon ii = new ImageIcon(this.getClass().getClassLoader().getResource(path));
    badgeIcon = ii.getImage();
    badgePath = path;
}


注意:非常重要:Java命名约定是类以大写字符开头。因此,将类名和文件名更改为:BadgeImgBadgeIMG

09-28 01:45