user1667191
user1667191

Reputation: 2527

Populating jtable from array under a loop

On each loop, it collects info from a certain file and stores it's contents in an array. The array should then create a new row per loop on the table. My problem is, is that it only creates 1 row. How can I fix this?

for (int i = 0; i < listOfFiles.length; i++) 
    {
        if (listOfFiles[i].isFile()) 
        {
            files = listOfFiles[i].getName();

            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
            iCount = humanReadableByteCount(listOfFiles[i].length(), true);

            if (files.toLowerCase().endsWith(".mp3"))
            {
                //jTextArea1.append("File name: " + files + " | Last Modified: " + sdf.format(listOfFiles[i].lastModified()) + " | Lenght: " + iCount + "\n");

                Object rowData[] = { files, sdf.format(listOfFiles[i].lastModified()), iCount };
                Object columnNames[] = { "Name", "Last Modified", "Size" };
                DefaultTableModel model = new DefaultTableModel(columnNames, 0);
                model.addRow(rowData);
                jTable1.setModel(model);
            }
        }
    }

Upvotes: 1

Views: 1668

Answers (2)

tb-
tb-

Reputation: 1290

You create a new model every time you cycle the loop. So every time, you have a new and empty model and you add 1 row to the empty model.

It should be like this:

Object columnNames[] = { "Name", "Last Modified", "Size" };
DefaultTableModel model = new DefaultTableModel(columnNames);
jTable1.setModel(model);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
for (int i = 0; i < listOfFiles.length; i++) 
    {
        if (listOfFiles[i].isFile() && listOfFiles[i].getName().toLowerCase().endsWith(".mp3")) 
        {
            files = listOfFiles[i].getName();
            iCount = humanReadableByteCount(listOfFiles[i].length(), true);
            model.addRow(new Object[]{ files, sdf.format(listOfFiles[i].lastModified()), iCount });
        }
    }

Upvotes: 2

Dan D.
Dan D.

Reputation: 32391

Create the model outside the loop. Set the table model outside the loop as well.

The only thing to do inside the loop is to add the new rows to the model.

Upvotes: 3

Related Questions