我使用此命令添加图像图标:
iadd.setIcon(new ImageIcon(getClass().getResource("add.png")));
top.add(iadd);
但是我得到了那个异常[线程中的异常“main”java.lang.NullPointerException]
答案 0 :(得分:0)
获取nullpointerException的可能性iadd
未初始化。
iadd.setIcon(new ImageIcon(getClass().getResource("add.png")));
或在行
top.add(iadd);
top
未初始化。
答案 1 :(得分:0)
我们需要更多信息才能正确帮助您。但请确保您实例化iadd
和top
。
要实例化,通常使用关键字new
。你应该有类似的东西:
X iadd = new X(...); // Probably ImageIcon in your case
Y top = new Y(...); // Probably some kind of List (ArrayList, LinkedList, etc.)
由于我们不知道类型,X
和Y
以及仅占位符;)
答案 2 :(得分:0)
我觉得你的异常来自getClass()。getResource(“add.png”)
在当前包中找不到资源?
答案 3 :(得分:0)
我想出了原因,这是因为我在定义后忘了验证imageicon:
iadd.setIcon(new ImageIcon(getClass().getResource("add.png")));
validate();
top.add(iadd);