start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
size = Integer.parseInt(sizeText.getText());
if(size<=1){
error = "Please key in size more than 1";
errorMsg.setText(error);
} else if(size>=5) {
error = "Please key in size less than 5";
errorMsg.setText(error);
} else {
//create Table 1
int sizer = size + 1;
JTable table1 = new JTable(sizer, sizer){
public boolean isCellEditable(int r, int c){
return false;
}
};
String[][] Object = new String[sizer][sizer];
String[][] Object2 = new String[sizer][sizer];
int i = 1;
Object[0][0] = " ";
for(int r = 1; r<sizer; r++){
String text1 = "Col " + r;
table1.setValueAt(text1, r, 0);
for(int c = 1; c<sizer; c++){
String text2 = "Row " + c;
table1.setValueAt(text2, 0, c);
}//first loop
}//second loop
for(int r = 1; r<Object.length; r++){
for(int c = 1; c<Object.length; c++){
Object2[r][c] = String.valueOf(i);
i++;
System.out.print(Object2[r][c]);
table1.setValueAt(Object2[r][c], r, c);
}
System.out.println();
}
for(int r = 1; r<Object2.length; r++){
for(int c = 1; c<Object2.length; c++){
int rnd = new Random().nextInt(size);
String temp = Object2[r][c];
System.out.println("1: "+temp+ "/" +Object2[r][c]);
Object2[r][c] = Object2[rnd][c];
System.out.println("2: "+Object2[r][c]+ "/" +Object2[rnd][c]);
Object2[rnd][c] = temp;
System.out.println("3: "+Object2[rnd][c]+ "/" + temp);
}//first loop
}//second loop
for(int r = 1; r<Object.length; r++){
for(int c = 1; c<Object.length; c++){
table1.setValueAt(Object2[r][c], r, c);
panel2.add(table1);
}//first loop
}//second loop
start.setEnabled(false);
start.setText("Good Luck!");
errorMsg.setVisible(false);
}}
});
我打印系统的原因是我要检查洗牌过程。事实证明,由于没有明显的原因,它的值为空值。我一直想弄清楚。我的JTable将有空格
答案 0 :(得分:1)
使用
初始化后for(int r = 1; r<Object.length; r++){
for(int c = 1; c<Object.length; c++){
Object2[r][c] = String.valueOf(i);
i++;
System.out.print(Object2[r][c]);
table1.setValueAt(Object2[r][c], r, c);
}
System.out.println();
}
数组包含以下内容(.
字段为null
)
0 1 2 3 4
0 . . . . .
1 . 1 2 3 4
2 . 5 6 7 8
3 . 9 10 11 12
4 . 13 14 15 16
它因为数组使用基于零的索引。
稍后当你洗牌时
int rnd = new Random().nextInt(size)
rnd
的值在以下范围0 <= rnd < size
。这意味着可以使用某些字符串值交换null
值。