繁体   English   中英

将 ArrayList 转换为 JTable 的二维数组

[英]Converting ArrayList to 2d array for 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; 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 行的普通表格。 有人可以帮忙吗?

您可以进行一些细微的调整,并且您应该能够按照自己的意愿进行操作。

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);
}

结果:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM