Converting ArrayList to 2d array for JTable

155 views Asked by At

I have an arrayList, consisting of a name, followed by a score, corresponding to the name. I would like to show this information in a Jtable, but there seems to be a problem. My table only shows 2 rows. Here's the code:

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

I noticed that if I add 2 more columns in columnNames[] , I get 4 results, instead of 2, but they're horizontal in the table under another username column and another scores column. I just want an ordinary table of 2 columns and 20-30 rows. Could anyone help?

1

There are 1 answers

0
Shar1er80 On

There are some slight adjustments you can make and you should be good to go on what you're wanting.

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

Results:

enter image description here