这是一个显示带有JTable的随机值的UI。它在所有数学程序中都可以正常工作,但是当我将它们应用到JTable时,会抛出ArrayIndexOutOfBoundsException。 ¿您能告诉我出什么问题了以及如何解决吗?最后,我要感谢您花费时间寻找这种故障。
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class RandomVals extends JFrame {
JTable a;
JScrollPane b;
public RandomVals () {
String [] header = new String[15]; //Fulfills 2D array
for (int i = 0; i < header.length; i++) { //with random numbers
header[i]=String.valueOf(i);
}
String [][] rows = new String[15][8];
for (int i = 0; i < rows.length; i++) {
System.out.println();
for (int j = 0; j < 8; j++) {
rows [i][j] = "Hi";
double foo = (Math.random()*2)+8;
rows [i][j] = String.format("%.2f",foo);
System.out.print(rows[i][j]+" ");
}
}
///////////// All above works but then an exception occurs //////////////
a = new JTable(rows, header); //Creating JTable
b = new JScrollPane(a);
b.setBounds(10,10,500,500);
add(b);
}
public static void main(String[] args) { //JFrame build up
RandomVals e = new RandomVals();
e.setSize(520,520);
e.setLocationRelativeTo(null);
e.setVisible(true);
e.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
您正在创建15列的标题...
String[] header = new String[15]; //Fulfills 2D array
for (int i = 0; i < header.length; i++) { //with random numbers
header[i] = String.valueOf(i);
}
但是随后创建具有15行8列的行数据
String[][] rows = new String[15][8];
for (int i = 0; i < rows.length; i++) {
System.out.println();
for (int j = 0; j < 8; j++) {
if (false) {
rows[i][j] = "Hi";
} else {
double foo = (Math.random() * 2) + 8;
rows[i][j] = String.format("%.2f", foo);
System.out.print(rows[i][j] + " ");
}
}
}
将以上内容更改为更多类似...
String[][] rows = new String[8][15];
for (int i = 0; i < rows.length; i++) {
System.out.println();
for (int j = 0; j < 15; j++) {
if (false) {
rows[i][j] = "Hi";
} else {
double foo = (Math.random() * 2) + 8;
rows[i][j] = String.format("%.2f", foo);
System.out.print(rows[i][j] + " ");
}
}
}
似乎为我工作