gpt4 book ai didi

java - JTable 抛出 ArrayIndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-12-02 01:17:33 24 4
gpt4 key购买 nike

这是一个使用 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] + " ");
}
}
}

似乎对我有用

关于java - JTable 抛出 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58314003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com