我无法确定为什么我的代码会得到nullPointer异常.我正在尝试使用Java和Clojure的组合编写一个swing应用程序.我有一个Clojure函数,该函数在我的JPanel子类中调用一个函数,而且我遇到了很多让我发疯的异常.
我已尽可能简化了我的代码,但仍然遇到这些错误.
(defn draw-state
"Draws the current state."
[state display]
(do-swing (.drawBlocks display)))
这是整个JPanel子类,尽管我认为唯一相关的部分是drawBlocks函数(该函数最终将替换blocks数组):
public class TDisplay extends JPanel {
private Block[] blocks = new Block[1];
/**
* Create the panel.
*/
public TDisplay() {
setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
setBackground(Color.WHITE);
setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
blocks[0] = new Block(3, 4, 0);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (Block b : blocks) {
if (b == null) continue;
switch (b.colour) {
case 0:
g.setColor(Color.WHITE);
break;
case 1:
g.setColor(Color.BLACK);
break;
}
g.fillRect(b.x * Block.SIZE, b.y * Block.SIZE, Block.SIZE, Block.SIZE);
}
}
public void drawBlocks() {
System.out.println("Hello world");
}
}
和堆栈跟踪:
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: java.lang.NullPointerException
at clojure.lang.AFn.run(AFn.java:28)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at clojure.lang.Reflector.invokeNoArgInstanceMember(Reflector.java:263)
at core$draw_state$fn__401.invoke(core.clj:43)
at clojure.lang.AFn.run(AFn.java:24)
... 8 more
我觉得我确实缺少一些明显的东西,感谢您的帮助.
谢谢!
解决方法:
调用draw-state的代码怎么样?是否有可能传入null进行显示?