我无法确定为什么我的代码会出现 nullPointer 异常。我正在尝试使用 Java 和 Clojure 的组合编写一个摇摆应用程序。我有一个 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
我觉得我错过了一些非常明显的东西,我会很感激任何帮助。
谢谢!