【发布时间】:2020-02-07 08:57:03
【问题描述】:
这是一个使用 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 列,但您的行数据只有 8 列……您的循环是否以错误的方式进行?即 8 行 15 列,而不是您设置的 15 行 8 列?
-
Anil M 情况相同,但算法不同,所以不是。
标签: java swing jtable indexoutofboundsexception