空指针异常 - 2D数组JButton

时间:2014-03-04 02:35:25

标签: arrays image nullpointerexception 2d 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]);
        }       
    }

1 个答案:

答案 0 :(得分:1)

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

// 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]);

    }

}