简体   繁体   中英

NullPointerException: adding JButtons in an array & panel

JButton buttonArray[][] = new JButton [6][7];
JPanel grid;
JButton b1;


grid.setLayout (new GridLayout(6,7,0,0));

    slot = new ImageIcon ("gameboard.png");

    for (int i = 0; i < 6; ++i)
    {
        for (int j = 0; j < 7; ++j)
        {
            b1 = new JButton (slot);
            buttonArray[i][j] = b1;
            buttonArray[i][j].setContentAreaFilled (false);
            buttonArray[i][j].setBorderPainted (false);
            grid.add(buttonArray[i][j]);
        }
    }

I am getting a NullPointerException which points to the grid.setLayout (new GridLayout(6,7,0,0)); part and to the new GameBoard(); which is in the main method at the bottom.

I add grid panel to another panel as well, together with other panels:

panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.add("North", panel1);
        panel.add("Center",grid);
        panel.add("South",panel2);
        add(panel);

I did initialize grid and buttonArray[][] already. What am I missing?

The grid variable is null as it has never been assigned an object. You need to either give it a new something or pass in its value via a setter method or constructor parameter.

More important than the actual solution to your current problem, is the knowledge of how to debug most common NullPointerExceptions. When you encounter a NullPointerException, you should carefully check all the variables on the line that throws the exception, find out which one is null, and then track back in your program to find out why it's null when you though otherwise.

You didn't initialize the grid variable:

JPanel grid; // null since it wasn't initialized
JButton b1;

grid.setLayout (new GridLayout(6,7,0,0));

You should just create some object there:

JPanel grid = new JPanel();
JButton b1;


grid.setLayout (new GridLayout(6,7,0,0));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM