java nested for() loop throws ArrayIndexOutOfBoundsException

Posted by Mike on Stack Overflow See other posts from Stack Overflow or by Mike
Published on 2010-05-11T19:33:20Z Indexed on 2010/05/11 19:44 UTC
Read the original article Hit count: 146

Filed under:
|
|

I'm working through a JPanel exercise in a Java book. I'm tasked with creating a 5x4 grid using GridLayout.

When I loop through the container to add panels and buttons, the first add() throws the OOB exception. What am I doing wrong?

package mineField;

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

@SuppressWarnings("serial")

public class MineField extends JFrame {

private final int WIDTH = 250;
private final int HEIGHT = 120;
private final int MAX_ROWS = 5; 
private final int MAX_COLUMNS = 4;

public MineField() {

    super("Minefield");

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Container mineFieldGrid = getContentPane();
    mineFieldGrid.setLayout(new GridLayout(MAX_ROWS, MAX_COLUMNS));

    // loop through arrays, add panels, then add buttons to panels.
    for (int i = 0; i < MAX_ROWS; i++) {
        JPanel[] rows = new JPanel[i];

        mineFieldGrid.add(rows[i], rows[i].getName());
        rows[i].setBackground(Color.blue);

        for (int j = 0; j < MAX_COLUMNS; j++) {
            JButton[] buttons = new JButton[i];             
            rows[i].add(buttons[j], buttons[j].getName());
        }
    }

    mineFieldGrid.setSize(WIDTH, HEIGHT);
    mineFieldGrid.setVisible(true);

}

public int setRandomBomb(Container con)
{

    int bombID;

    bombID = (int) (Math.random() * con.getComponentCount());
    return bombID;


}
/**
 * @param args
 */
public static void main(String[] args) {

    //int randomBomb;
    //JButton bombLocation;

    MineField minePanel = new MineField();
    //minePanel[randomBomb] = minePanel.setRandomBomb(minePanel);

}

}

I'm sure I'm over-engineering a simple nested for loop. Since I'm new to Java, please be kind. I'm sure I'll return the favor some day.

© Stack Overflow or respective owner

Related posts about java

Related posts about jpanel