Java 如何为自定义类创建2d arrayobject

Java 如何为自定义类创建2d arrayobject,java,multidimensional-array,nullpointerexception,jframe,jbutton,Java,Multidimensional Array,Nullpointerexception,Jframe,Jbutton,我有一个名为ButtonList的自定义类,就像按钮列表一样,我将所有进入窗口的按钮添加到按钮列表的2d数组对象中 ButtonList[][] buttonList; buttonList = new ButtonList[5][3]; 当我试图添加 将按钮添加到按钮列表 this.buttonList[column][row].addButton(buttonImage); ButtonList和addButton方法如下所示: static class ButtonList{

我有一个名为ButtonList的自定义类,就像按钮列表一样,我将所有进入窗口的按钮添加到按钮列表的2d数组对象中

ButtonList[][] buttonList;
buttonList = new ButtonList[5][3];
当我试图添加 将按钮添加到按钮列表

this.buttonList[column][row].addButton(buttonImage);
ButtonList和addButton方法如下所示:

static class ButtonList{
    int column = 0;
    int row = 0;
    JButton[][] arrayButton = new JButton[this.column][this.row];

    void addButton(JButton BUTTON){ 
        arrayButton[this.column][this.row] = BUTTON;
        System.out.println("Row: " + this.row + " Column: " + this.column);
        this.column += 1;
        this.row += 1;
        System.out.println("button inserted at " + this.row);
    }//end addButton
我做错了什么? 谢谢

在调用构造函数之前初始化数组。所以此时,列和行仍然为0。然后初始化[0][0]的数组。这就是为什么以后会出现空指针异常,即使您可能在构造函数中或以后在任何方法中更改了行和列的值。但在创建时,它们是0。 而且

           arrayButton[this.column][this.row] = BUTTON;
这很可能会给您带来一个越界异常,因为java中的数组是0索引的,所以您的有效范围是[0,column-1][0,row-1],所以您可能还需要解决这个问题

JButton[][] arrayButton = new JButton[this.column][this.row];
这一行创建了一个二维数组(无需初始化),实际上相当于:

JButton[][] arrayButton = new JButton[0][0];
0恰好是当时列和行的值。更改这两个变量的值不会对数组本身产生任何影响

解决方案:
如果预先知道列和行的最大值,请使用该值创建数组。如果没有,请使用ArrayList,以后您可以更改大小。

您应该将arrayButton初始化为
arrayButton[this.column][this.row]=new JButton()addButton()
方法中的code>中。我没有为该类创建构造函数。。它是默认的构造函数。然而,在你的建议之后,我创建了我的构造函数,看起来是这样的:JButton[][]arrayButton;ButtonList(){arrayButton=new JButton[this.column][this.row];}好的,您仍然需要为列和行指定正确的大小,以便真正创建数组。尝试将列和行的值设为4,然后查看程序的流程。没有配偶,仍然没有骰子:(这很烦人。你想要一份代码副本吗?@sabbibJAVA是的,这会很有帮助。它仍然不起作用,我已经分享了上面的代码。如果你能帮我看看,我会很高兴的。JButton的总数是多少?
JButton[][] arrayButton = new JButton[0][0];