我正在通過Java書中的JPanel練習。我的任務是使用GridLayout創建一個5x4網格。java嵌套for()循環拋出ArrayIndexOutOfBoundsException
當我通過容器循環添加面板和按鈕時,第一個add()會引發OOB異常。我究竟做錯了什麼?
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);
}
}
我敢肯定,我在工程一個簡單的嵌套for循環。由於我是Java新手,請善待。我相信有一天我會回來的。
好的,所以我分配了JPanel []數組w/MAX_ROWS。我如何初始化JPanel數組和什麼值? – 2010-05-11 21:32:31
對於在0和'MAX_ROWS-1'之間的每個'k',JPanel [k] = new JPanel()。 – IVlad 2010-05-11 21:43:51
忽略最後一個。 因此JPanel [] rows = new JPanel [MAX_ROWS]聲明併爲我的數組分配內存。現在,我如何使用JPanel對象初始化數組?我假設我然後分配JButtons行[i] .add(),對吧? – 2010-05-11 21:47:16