user1494890
user1494890

Reputation:

Why does this code have the error: NullPointerException?

This code is part of a Tic Tac Toe program that I'm making with Java Swing. Why does it return NullPointerException when the for statement to add the buttons is added?

import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;

public class TicTacToeGui extends JFrame
{
    public final static int r = 3;
    public final static int c = 3;
    TicTacToeGui()
    {   
         JButton[][] button = new JButton[3][3];
         JPanel panel = new JPanel();
         panel.setLayout(new GridLayout(r, c));
         JLabel label = new JLabel("This is a tic tac toe game.");
         for(int i = 0; i < r; i++)
         {
            for(int j = 0; j < c; j++)
            {
                panel.add(button[i][j]);
            }
         }
         this.add(label);
         this.add(panel);
         this.setSize(400, 400);
         this.setVisible(true);
         this.setDefaultCloseOperation(EXIT_ON_CLOSE);
     }


    public static void main(String [] args)
    {
        new TicTacToeGui();
    }
}

Upvotes: 0

Views: 124

Answers (3)

nolegs
nolegs

Reputation: 608

The line JButton[][] button = new JButton[3][3]; doesn't actually initialize the buttons. You need to create new buttons and stick them in here.

Upvotes: 2

Hans Z
Hans Z

Reputation: 4744

You never initialize any JButton. When you declare

JButton[][] button = new JButton[3][3];

It just creates an empty 3x3 array of null, and you have to manually go through each spot in your array of arrays and initialize with

button[row][col] = new JButton("");

Upvotes: 2

Rocky Pulley
Rocky Pulley

Reputation: 23301

because button[0][0] is null. You initialize the array but none of the elements in it.

Upvotes: 2

Related Questions