Java 将ArrayList转换为JTable的2d数组
我有一个arrayList,由一个名称和一个分数组成,对应于该名称。我想在Jtable中显示此信息,但似乎存在问题。我的表格只显示2行。代码如下:Java 将ArrayList转换为JTable的2d数组,java,arrays,arraylist,jtable,Java,Arrays,Arraylist,Jtable,我有一个arrayList,由一个名称和一个分数组成,对应于该名称。我想在Jtable中显示此信息,但似乎存在问题。我的表格只显示2行。代码如下: int numberOfScores = allScores.size()/6; //arrayList of a username, followed by a score Object[][] newArrayContent = new Object[numberOfScores][6]; for(int x = 0;
int numberOfScores = allScores.size()/6; //arrayList of a username, followed by a score
Object[][] newArrayContent = new Object[numberOfScores][6];
for(int x = 0; x<numberOfScores; x++){
for(int z = 0; z < 6; z++){
int y = 6 * x;
newArrayContent [x][z] = allScores.get(y+z);
System.out.println(newArrayContent [x][z].toString());
}
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Object rowData[][] = newArrayContent;
Object columnNames[] = { "username", "score"};
JTable table = new JTable(newArrayContent, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
int numberOfScores=allScores.size()/6//用户名的arrayList,后跟分数
Object[]newArrayContent=新对象[numberOfScores][6];
对于(intx=0;x来说,您可以进行一些轻微的调整,您应该能够很好地继续您想要的内容
public static void main(String[] args) throws Exception {
List<String> allScores = new ArrayList<>();
allScores.add("John Doe");
allScores.add("95");
allScores.add("Jane Doe");
allScores.add("100");
allScores.add("Stack Overflow");
allScores.add("75");
// Divide by 2instead of 6, since every 2 items makes a row
int numberOfScores = allScores.size() / 2; // ArrayList of a username followed by a score
Object[][] newArrayContent = new Object[numberOfScores][2];
// Counter to track what row is being created
int rowIndex = 0;
// Loop through the entire ArrayList. Every two items makes a row
for (int i = 0; i < allScores.size(); i += 2) {
newArrayContent[rowIndex][0] = allScores.get(i);
newArrayContent[rowIndex][1] = allScores.get(i + 1);
rowIndex++;
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Object rowData[][] = newArrayContent;
Object columnNames[] = {"username", "score"};
// Use rowData instead of newArrayContent
JTable table = new JTable(rowData, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
publicstaticvoidmain(字符串[]args)引发异常{
List allScores=new ArrayList();
所有分数。添加(“John Doe”);
所有分数。加上(“95”);
所有分数。添加(“Jane Doe”);
所有分数。加上(“100”);
添加(“堆栈溢出”);
所有分数。加上(“75”);
//除以2而不是6,因为每2个项目构成一行
int numberOfScores=allScores.size()/2;//用户名的数组列表,后跟一个分数
Object[]newArrayContent=newobject[numberOfScores][2];
//计数器以跟踪正在创建的行
int rowIndex=0;
//循环遍历整个ArrayList。每两个项组成一行
对于(int i=0;i
结果:
numberOfScores的值是多少?
代码运行良好,因此问题可能在于变量的值numberOfScores是arrayList的大小。谢谢,我修复了它。代码中的所有这6个数字都来自代码的另一个实现,我将所有的6改为2,效果非常好。:)