Homer Homer
Homer Homer

Reputation: 57

Clear Two Dimensional Array

How can I clear a 6x6 "table", so that anything in it is cleared? (I made the clearbutton already with ActionListener...etc)

        //other code above that creates window, below is the code that creates the table I need to clear

         square = new JTextField[s][s];
    for (int r=0; r!=s; r++) {
        symbols[r] = new JTextField();
        symbols[r].setBounds(35+r*35, 40, 30, 25);
        win.add(symbols[r], 0);
        for (int c=0; c!=s; c++) {
            square[r][c] = new JTextField();
            square[r][c].setBounds(15+c*35, 110+r*30, 30, 25);
            win.add(square[r][c], 0);
        }
    }
    win.repaint();
}

Upvotes: 1

Views: 17428

Answers (3)

Ivan Kovtun
Ivan Kovtun

Reputation: 693

Here is one line solution:

Arrays.stream(square).forEach(x -> Arrays.fill(x, null));

Upvotes: 1

Eric B.
Eric B.

Reputation: 24411

Loop over the array and and set each element to null. You can use the java.utils.Arrays utility class to make things cleaner/neater.

for( int i = 0; i < square.length; i++ )
   Arrays.fill( square[i], null );

Upvotes: 2

MadProgrammer
MadProgrammer

Reputation: 347194

Something like...

for (int index = 0; index < square.length; index++) {
    square[index] = null;
}
square = null;

Will do more then the trick (in fact the last line would normally be enough)...

If you're really paranoid...

for (int index = 0; index < square.length; index++) {
    for (int inner = 0; inner < square[index].length; inner++) {
        square[index][inner] = null;
    }
    square[index] = null;
}
square = null;

Upvotes: 0

Related Questions