Reputation: 63
I've tried a couple of ways to do this...Basically I'm trying to create a tic tac toe board for an assignment and maybe I'm missing something obvious, but I get a "not a statement" error when I try to create the buttons. Here's the code I've got:
int rows = 3;
int cols = 3;
JPanel ticTacToeBoard = new JPanel();
ticTacToeBoard.setLayout(new GridLayout(3, 3));
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
JButton gameButton[i] = new JButton[];
ticTacToeBoard.add(gameButton[i]);
}
}
Thanks...
Upvotes: 0
Views: 62
Reputation: 36601
The following is incorrect
JButton gameButton[i] = new JButton[];
There is no need for the []. Just do
JButton gameButton = new JButton();
ticTacToeBoard.add(gameButton);
If you want to store the buttons in an array as well, you should have code like
JButton[] buttonArray = new JButton[10];//or whatever length
...
JButton gameButton = new JButton();
buttonArray[i] = gameButton;
Upvotes: 4
Reputation: 328568
You need to declare your array somewhere:
JButton[] gameButton = new JButton[size];
Then in your loop:
gameButton[i] = new JButton();
For example:
JButton[] gameButton = new JButton[rows * cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
gameButton[i] = new JButton();
ticTacToeBoard.add(gameButton[i]);
}
}
You can also have a look at the Java tutorial on arrays.
Note: Is there a reason why you don't use a List
instead of an array? If would make your life easier.
Upvotes: 5