我有一个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; 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);
我注意到如果我在columnNames[]
中再添加2个列,我会得到4个结果,而不是2个,但它们在另一个用户列和另一个得分列下的表格中是水平的。我只想要一个2列和20-30行的普通表。有人可以帮忙吗?
答案 0 :(得分:0)
你可以做一些轻微的调整,你应该好好继续你想要的。
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);
}
结果: