com*_*rix 0 java arrays swing jpanel
我已经尝试了几种方法来做到这一点...基本上我正在尝试为一个任务创建一个tic tac toe board,也许我错过了一些明显的东西,但当我发现时,我得到一个"非声明"错误尝试创建按钮.这是我得到的代码:
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]);
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢...
你需要在某个地方声明你的数组:
JButton[] gameButton = new JButton[size];
Run Code Online (Sandbox Code Playgroud)
然后在你的循环中:
gameButton[i] = new JButton();
Run Code Online (Sandbox Code Playgroud)
例如:
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]);
}
}
Run Code Online (Sandbox Code Playgroud)
注意:您是否有理由不使用List数组而不是数组?如果会让你的生活更轻松.