简体   繁体   English

如何一次创建100个JButton

[英]How to create 100 JButtons at once

So I am supposed to make a game of Battleship which is 10x10. 所以我应该做一个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. 我想知道是否有一种方法可以立即创建和实例化100个JButton,而无需手动进行创建/实例化。 Each with a number at the end corresponding to it's position on the board. 每个数字的末尾都有一个数字,对应于它在板上的位置。 eg. 例如。 00 for col 0 row 0. 00代表第0行第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来设置按钮的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM