空指针异常 - 二维数组 JButton


    // 8x8 shiny button layout
    JButton[][] buttons = new JButton[8][8];
    for (int i=0; i<8; i++) {
        for (int j=0; j<8; j++) {
            buttons[i][j].setLocation(10+j*55, 10+i*55);
            --->buttons[i][j].setSize(69,69);
            int r = 1 + (int)(Math.random()*((7-1)+1));
            buttons[i][j] = new JButton(icons[r]);
            add(buttons[i][j]);
        }
    }

上面的代码给了我问题,我不断在带有箭头的代码上收到空指针异常。我是论坛和Java代码的新手。请并感谢您的帮助


我不知道我做了什么,但我的代码现在可以工作了

    // 8x8 shiny button layout
    JButton[][] shinyButton = new JButton[8][8];
    for (int i=0; i<8; i++) {
        for (int j=0; j<8; j++) {
            int r = 1 + (int)(Math.random()*((6-1)+1));
            shinyButton[i][j] = new JButton(icons[r]);
            shinyButton[i][j].setLocation(10+j*69, 10+i*69);
            shinyButton[i][j].setSize(69,69);
            add(shinyButton[i][j]);
        }       
    }

在设置某些属性之前,先尝试初始化按钮

// 8x8 shiny button layout
JButton[][] buttons = new JButton[8][8];
for (int i=0; i<8; i++) {
    for (int j=0; j<8; j++) {
        /*Initialize a button*/
        int r = 1 + (int)(Math.random()*((7-1)+1));
        buttons[i][j] = new JButton(icons[r]);
        buttons[i][j].setLocation(10+j*55, 10+i*55);
        buttons[i][j].setSize(69,69);      
        add(buttons[i][j]);
    }
}

最新更新