我想按循环创建
但是当我编写代码
时,按钮有array2Dprivate JButton cells[][];
// Constructor
public SliderGameFrame() {
JPanel panel = new JPanel();
this.add(panel);
for (int i = 1; i <= cells.length; i++) {
for (int j = 1; j <= cells.length; j++) {
cells[i][j] = new JButton(" " + i);
panel.add(cells[i][j]);
}
}
}
它没有工作,错误按摩是 java.lang.NullPointerException
答案 0 :(得分:1)
更改:
for (int i = 1; i <= cells.length; i++) {
for (int j = 1; j <= cells.length; j++) {
成:
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells.length; j++) {
二维数组的索引从0开始到维度-1。