I have a 3x3 array of MSTextField which is a class I created which extends JTextField . I'm trying to set all of the text fields to display the empty string ( "" ). My problem is I'm getting a nullPointerException at the end of the method which is supposed to do this. I think the problem might be that I haven't initialized the array yet (earlier I thought that I was doing this by setting each text field to "" but I think I was wrong). How do I initialize an array of MSTextField so that I can set the text? Also, once they're initialized will textFieldArray[row][column].setText( "" ); at the end of my for loops work?

Dani AI

Generated

As explained, the NullPointerException in this situation normally means one of two things: the 2‑D array reference itself was never allocated, or the individual cells were never constructed. For Swing text fields the correct sequence is (1) allocate the array object, (2) instantiate each MSTextField and put it into the array, then (3) manipulate those instances. Once each cell holds a real MSTextField instance, calling its text methods will work (as discovered).

A minimal pattern that initializes a 3×3 grid and adds it to a panel:

MSTextField[][] fields = new MSTextField[3][3];
JPanel panel = new JPanel(new GridLayout(3, 3));

for (int r = 0; r < fields.length; r++) {
    for (int c = 0; c < fields[r].length; c++) {
        fields[r][c] = new MSTextField("");   // construct with empty text
        panel.add(fields[r][c]);
    }
}

Safety notes and small troubleshooting checks:

  • If a NullPointerException still occurs, log or breakpoint to see whether the array variable itself is null or whether a particular cell is null.
  • When updating text later, either ensure all cells were created up front or check for null before calling methods on a cell.
  • All Swing component creation and updates must run on the Event Dispatch Thread; wrap GUI construction in SwingUtilities.invokeLater to avoid odd timing bugs.

If the goal is a spreadsheet-like editable grid, using JTable with a custom TableModel is generally easier and more robust than managing a matrix of text fields.

Recommended Answers

All 2 Replies

When using arrays of objects, there are two steps.
One: create the array object. (Yes arrays are very like objects)
Two: fill the array with the objects

You probably have not done step two.

textFieldArray[j] = new TextField(); // set i,j element to a TextField

Thank you! I don't know why I couldn't figure that out myself. I tend to over-think things expecting them to be harder than they really are. Thanks Again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.