Java 具有自定义行和列的二维阵列

Java 具有自定义行和列的二维阵列,java,arrays,swing,awt,Java,Arrays,Swing,Awt,我需要创建一个2d数组,第一行有5行6列,其余的是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。这是不可能的 但是,您可以创建一个6x6数组,而不是在不想使用的每一行中使用第6列 { 0

我需要创建一个2d数组,第一行有5行6列,其余的是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。

这是不可能的

但是,您可以创建一个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  }

您可以通过两个步骤初始化阵列:

// 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];
    }
}
//初始化第一个维度
私有静态JButton[]]b=新JButton[5][];
//初始化第二个维度
静止的{
b[0]=新的JButton[6];
for(int i=1;i
当您仅初始化第一个维度时,它会创建一个行数组,其中每一行都是
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];
    }
}
JButton[]]s=新的JButton[5][];
对于(int i=0;i<5;i++){
如果(i==0){
s[i]=新的JButton[6];
}否则{
s[i]=新的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]);

           }

        } 
for(int i=0;i对于(int j=0;j),您可能希望为您正在使用的语言标记此问题“用例”是什么为此?它可能在逻辑上适合于两个数组:一个是1x6,另一个是5x5。管理它也可能更简单。好吧,在我的情况下,管理一个数组会更简单。@潜伏者实际上另一个是4x5,而不是5x5。但我同意分离的想法。@Joffrey是的,对不起,我算错了。:pBoth分支,如果正在做的话同样的事情。你没有考虑变量的静态上下文。此外,有一个键值,你可能是5,而不是6。对于定型是固定的,但是另一个答案涉及静态上下文。是的,这是可能的。看看我的答案。“你的方式”是非常痛苦的使用,如果你有一个256×256数组?复制粘贴?