Search code examples
javaswingnullpointerexceptionjtextfieldgrid-layout

JTextField Array issue


So I'm working with a two-dimensional array of JTextFields for a Sudoku program.

public JTextField[][] userInputArray = new JTextField[9][9];

Now. I'm getting a continual null pointer exception, and can't discern how to fix it. It comes from firing this method:

    public void showTextFields()
{
    int rowCounter = 0;
    int columnCounter = 0;

    for (rowCounter = 0; rowCounter <= 8; rowCounter += 1)
    {
        for (columnCounter = 0; columnCounter <= 8; columnCounter += 1)
        {
            pane.setLayout(new GridLayout(9, 9));
            //pane.add(userInputArray[rowCounter][columnCounter]);
            //userInputArray[rowCounter][columnCounter].setColumns(1);
            //userInputArray[rowCounter][columnCounter].setVisible(true);
        }
    }
}

Everything commented out will throw the nullpointerexception.

Optimally, my goal is to display the JTextFields on screen, assigning them on the grid.

NullPointerException occurs at pane.add(...)


Solution

  • While you have created the 2D array to house your fields, you need to instantiate the JTextField components in your array.

    for (int i =0; i < userInputArray.length; i++) {
       for (int j =0; j < userInputArray[0].length; j++) {
          userInputArray[i][j] = new JTextField();
       }
    }