NullPointerException: agregar JButtons en una matriz y 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.

añado grid panel t o 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?

preguntado el 08 de febrero de 14 a las 17:02

Te falta un grid = new ... en algún lugar... -

Donde estas inicializando grid? You haven't shown that. If you're not, then presumably it still has a null valor... -

I initialized everything outside the constructor -

@user3026693: the JVM is telling you different. Believe the JVM. Show us where you initialize grid. -

2 Respuestas

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.

Respondido 08 Feb 14, 17:02

Thanks I'm able to fix it, I guess I just need to code a little bit cleaner - user3026693

@user3026693: see edit to answer. Learning to debug NPE's is a necessary skill to have as you will encounter many of these in the future. - Aerodeslizador lleno de anguilas

No inicializaste el 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));

Respondido 08 Feb 14, 17:02

Well this is rather embarrassing, I should've looked through my code further and more carefully but thank you for the answer!! - user3026693

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.