So I am supposed to make a game of Battleship which is 10x10. I was wondering if there was a way to create and instantiate 100 JButtons at once without having to go through and create/instantiate each one manually. Each with a number at the end corresponding to it's position on the board. eg. 00 for col 0 row 0.
Thanks,
Jeff
JButton[][] button = new JButton[10][10];
String str = "fireshot";
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
button[i][j] = new JButton(str+i+j);
}
}
JButton [][] buttons = new JButton[numRows][numCols];
for (int i = 0; i < numRows; ++i) {
for (int j = 0; j < numCols; ++j) {
buttons[i][j] = new JButton(String.format("Button %d, %d", i, j));
}
}
使用JTable
并将您自己的单元格渲染器指定为使用单个JButton的单元格渲染器。
您必须设置GridLayout来设置按钮的位置。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.