[英]2D Array with a custom rows and columns
我需要在第一行中创建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。
您可以分两步初始化数组:
// 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
。
在第二步中,您将创建所需长度的每一行。
这是不可能的。
但是,您可以创建6x6数组,而不必在不需要的每一行中使用第六列。
{ 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 }
这样的衣服会吗?
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];
}
}
我真的想通了。 这是我的方法:
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]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.