JTable 抛出 ArrayIndexOutOfBoundsException

JTable throws an ArrayIndexOutOfBoundsException

这是一个 UI,它使用 JTable 显示随机值。它适用于所有数学程序,但是当我将它们应用于 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 列的 header...

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] + " ");
        }
    }
}

似乎对我有用