尝试在方法中创建新的ImageIcon时出现问题

时间:2018-07-18 13:30:03

标签: java import path imageicon

我试图通过生成路径的自定义字符串来创建返回ImageIcon的方法(如果您看到代码,则更容易说明)

    public ImageIcon getIcone() {
       String path = "/party/blty/guesswho/"+id+".png";
       ImageIcon img = new ImageIcon(Personagem.class.getResource(path));
       return img;
}

当我进入主类时,此方法在构造函数类中 并尝试做

    Personagem p11 = new Personagem(11, "Alex", 
    "/party/blty/guesswho/11x.png", "/party/blty/guesswho/11x.png");    
    JButton botao11 = new JButton("");
    botao11.setIcon(p11.getIcone());

我遇到了这个错误

    java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(Unknown Source)
    at party.blty.guesswho.Personagem.getIcone(Personagem.java:26)
   at party.blty.guesswho.Janela.initialize(Janela.java:68)
    at party.blty.guesswho.Janela.<init>(Janela.java:40)
    at party.blty.guesswho.Janela$1.run(Janela.java:29)

如果我创建一个像这样的字符串

    String path = "/party/blty/guesswho/11x.png";

并用它起作用的方法替换它,但是当我尝试使用一个变量生成自定义字符串时出现错误,是什么原因导致此错误?我在做错什么吗?

0 个答案:

没有答案