Wednesday, May 2, 2012

Java for loop not completing properly

Ok, so I'm trying to add an array of 64 JButtons to a JFrame with and 8 by 8 grid layout (chess board type thing). Here's the relevant code section:



public class othello implements ActionListener{
int [][] board = new int[8][8];
JFrame window = new JFrame();
JButton[] buttons = new JButton[64];

public othello(){

window.setSize(400,400);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new GridLayout(8,8));
window.setVisible(true);
for (int i=0;i<64;i++){
buttons[i] = new JButton("");
buttons[i].addActionListener(this);
window.add(buttons[i]);
}
for (int i=0;i<8;i++){
for (int j=0;j<8;j++){
board[i][j]=2;
}
}
board[3][3]=0;board[4][4]=0;
board[3][4]=1;board[4][3]=1;
}

public void actionPerformed(ActionEvent e){
for (int i=0;i<8;i++){
for (int j=0;j<8;j++){
if(e.getSource()==buttons[i]){
buttons[i].setEnabled(false);
board[i][j]=1;
check();
}
}
}
}

public static void main (String[] args){
new othello();
}


}



What this code results in is a seemingly random number of buttons actually being added. Occasionally it adds all 64, more commonly it adds perhaps half or so, it always starts properly but stops at an arbitrary point (I tested by having the button labels count up).



I added some println's to see if the loop itself was actually completing, no problem there, it's going round the loop all 64 times, it just stops adding buttons at some point.



I'm something of a beginner at Java so I'm sure it's something really simple and stupid, but I currently have no idea what's going wrong. Can anyone help?



Edited for more code.





No comments:

Post a Comment