【问题标题】:JTable throws an ArrayIndexOutOfBoundsException [duplicate]JTable 抛出 ArrayIndexOutOfBoundsException [重复]
【发布时间】: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


【解决方案1】:

您正在创建一个包含 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] + " ");
        }
    }
}

似乎对我有用

【讨论】:

  • 哦,非常感谢。我没有检查那个细节。多么愚蠢的错误xd
  • @Steve 欢迎来到森林,注意树木
  • 哈哈,似乎是完美主义者的任务。
猜你喜欢
  • 2012-03-26
  • 2011-03-22
  • 1970-01-01
  • 2017-08-10
  • 1970-01-01
  • 2016-11-09
  • 2023-03-16
  • 1970-01-01
  • 2014-06-06
相关资源
最近更新 更多