-->

宣布新的ImageIcon时的NullPointerException(nullpointerexc

2019-10-19 04:01发布

我试图在同一窗口中加载多个图像,这样可以防止大量的复制和粘贴,我做了名为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)

Answer 1:

badgePathnull

构造函数使用badgePath作为参数的ImageIcon构造,但它并没有先初始化。 使用这样的构造函数:

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

:非常重要:Java的命名约定是类以大写字符。 所以改变类名和文件名: BadgeImgBadgeIMG



Answer 2:

this.getClass().getClassLoader().getResource(badgePath))

你badgePath是null. 请图像路径初始化。

当你想有一个形象,你应该给一个路径。 现在它是null 。 给予减速路径或使用它解决您的问题之前将值分配给它。

  String badgePath="some/valid/path";


文章来源: nullpointerexception when declaring new ImageIcon