无法添加imageIcon

时间:2013-04-15 14:09:33

标签: java exception button imageicon

我使用此命令添加图像图标:

iadd.setIcon(new ImageIcon(getClass().getResource("add.png")));
top.add(iadd);

但是我得到了那个异常[线程中的异常“main”java.lang.NullPointerException]

4 个答案:

答案 0 :(得分:0)

获取nullpointerException的可能性iadd未初始化。

iadd.setIcon(new ImageIcon(getClass().getResource("add.png")));

或在行

top.add(iadd);

top未初始化。

答案 1 :(得分:0)

我们需要更多信息才能正确帮助您。但请确保您实例化iaddtop

要实例化,通常使用关键字new。你应该有类似的东西:

X iadd = new X(...); // Probably ImageIcon in your case
Y top = new Y(...); // Probably some kind of List (ArrayList, LinkedList, etc.)

由于我们不知道类型,XY以及仅占位符;)

答案 2 :(得分:0)

我觉得你的异常来自getClass()。getResource(“add.png”)

在当前包中找不到资源?

答案 3 :(得分:0)

我想出了原因,这是因为我在定义后忘了验证imageicon:

iadd.setIcon(new ImageIcon(getClass().getResource("add.png")));
validate();
top.add(iadd);