我正在通过我的简单游戏应用程序简化从700行到177的所有内容,以消除重复。当我尝试运行我的应用程序时,我被Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
抛向我。我知道这意味着什么(来自阅读this),我知道它与我如何做actionListener
有关,但我不知道如何。
我按照我遇到的处理数组和JButtons
的所有教程,但必定会出现一些小问题。 private JButton[][] blocks = new JButton[rows][cols]
被正确声明,所以不是这样,我没有改变我之前版本的代码blocks[i][j].addActionListener(this)
的方式,除了我用{更改了block1,block2 ...等的事实{1}}。
以下是向我投掷的内容:
block[i][j]
这是我的代码:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at blox.Blox.game(Blox.java:105)
at blox.Blox.access$000(Blox.java:25)
at blox.Blox$1.run(Blox.java:173)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:727)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:697)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
答案 0 :(得分:4)
问题可能来自你的循环:
for(int i=0; i<rows; i++) {
for(int j=0; i<cols; j++) {
block[i][j].setIcon(randomizer());
block[i][j].addActionListener(this);
boardBg.add(block[i][j]);
}
}
block[i][j]
未初始化。首先将它们初始化为:
for(int i=0; i<rows; i++) {
for(int j=0; i<cols; j++) {.
block[i][j] = new JButton();
block[i][j].setIcon(randomizer());
block[i][j].addActionListener(this);
boardBg.add(block[i][j]);
}
}