我需要在第一行创建5行6列的2d数组,其余的是5列
所以看起来像这样
{ 0 0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0 }
有没有办法这样做?
截至目前我只有这个,它创建了6行5列:
private static JButton[][] b = new JButton[6][5];
updtae:我正在使用Java。
答案 0 :(得分:2)
您可以分两步初始化数组:
// initialize the first dimension
private static JButton[][] b = new JButton[5][];
// initialize the second dimension
static {
b[0] = new JButton[6];
for (int i = 1; i < b.length; i++) {
b[i] = new JButton[5];
}
}
初始化第一个维度时,会创建一个行数组,其中每一行都为null
。
在第二步中,您将创建所需长度的每一行。
答案 1 :(得分:0)
这是不可能的。
但是,您可以创建一个6x6数组,而不是在您不想要的每一行中使用第6列。
{ 0 0 0 0 0 0
0 0 0 0 0 null
0 0 0 0 0 null
0 0 0 0 0 null
0 0 0 0 0 null }
答案 2 :(得分:0)
这样的事情适合吗?
JButton[][] s = new JButton[5][];
for (int i = 0; i< 5; i++){
if (i == 0) {
s[i] = new JButton[6];
} else {
s[i] = new JButton[5];
}
}
答案 3 :(得分:0)
我实际上已经明白了。这是我的方式:
private static JButton[][] b = {{new JButton(), new JButton() , new JButton() , new JButton() , new JButton() , new JButton() },
{new JButton(), new JButton() , new JButton() , new JButton() , new JButton()},
{new JButton(), new JButton() , new JButton() , new JButton() , new JButton()},
{new JButton(), new JButton() , new JButton() , new JButton() , new JButton()},
{new JButton(), new JButton() , new JButton() , new JButton() , new JButton()}};
然后我只是将它们添加到面板
for (int i = 0; i < b.length; i++) {
for (int j = 0; j <b[i].length; j++) {
panel.add(b[i][j]);
}
}