2

我不断收到这些错误,我不知道为什么。我知道这与按钮有关,但我不知道如何修复它们。

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at java.awt.Container.addImpl(Container.java:1090)
    at java.awt.Container.add(Container.java:410)
    at LightsChasingSolver.<init>(LightsChasingSolver.java:45)
    at LightsChasingUI$2.actionPerformed(LightsChasingUI.java:153)

这是我的代码

final JFrame frame2 = new JFrame("Lights Chasing Solver");
GridLayout gridLay = new GridLayout(2,1);
GridLayout grid = new GridLayout(5,5);
JPanel mainPanel = new JPanel(grid);        
JPanel legendPanel = new JPanel();

final JButton[][] sht = new JButton[5][5];

for(i=0;i<5;i++){
    for(j=0;j<5; j++) mainPanel.add(sht[i][j]);
}
4

1 回答 1

2

按钮数组中的每个元素都是空的。您不能将空组件添加到容器中。

for(int i = 0; i < 5; i++) {
    for(int j = 0; j < 5; j++) {
        sht[i][j] = new JButton("Hello"); // add this line
        mainPanel.add(sht[i][j]);
    }
 }
于 2013-03-17T16:17:17.750 回答