How to add row dynamically in JTable

Uday A. Navapara picture Uday A. Navapara · Mar 13, 2014 · Viewed 87.6k times · Source

I want to add the row dynamically in JTable and I have writen the following code for that:

    tblTaskList = new JTable();
    tblTaskList.setShowVerticalLines(false);
    tblTaskList.setCellSelectionEnabled(true);
    tblTaskList.setColumnSelectionAllowed(true);
    tblTaskList.setBorder(new LineBorder(null));
    for (int count = 1; count <= 10; count++) {
        tblTaskList.setModel(new DefaultTableModel(new Object[][] { {
                count, "title1", "start", "stop", "pause", "status" }, },
                new String[] { "status", "Task Title", "Start", "Stop",
                        "Pause", "Status" }));
    }
    tblTaskList.getColumnModel().getColumn(0).setPreferredWidth(31);
    tblTaskList.getColumnModel().getColumn(1).setPreferredWidth(346);
    tblTaskList.getColumnModel().getColumn(2).setPreferredWidth(33);
    tblTaskList.getColumnModel().getColumn(3).setPreferredWidth(31);
    tblTaskList.getColumnModel().getColumn(4).setPreferredWidth(28);

    tblTaskList.setBounds(93, 34, 614, 160);
    frmTaskList.getContentPane().add(tblTaskList);

The problem is that only the last row is added, i.e. count print the value 10 in first column,,,can anyone explain how to solve the problem?

Answer

user3440678 picture user3440678 · Mar 21, 2014
 // create object of table and table model
 JTable tbl = new JTable();
 DefaultTableModel dtm = new DefaultTableModel(0, 0);

// add header of the table
String header[] = new String[] { "Prority", "Task Title", "Start",
            "Pause", "Stop", "Statulses" };

// add header in table model     
 dtm.setColumnIdentifiers(header);
   //set model into the table object
       tbl.setModel(dtm);

     // add row dynamically into the table      
for (int count = 1; count <= 30; count++) {
        dtm.addRow(new Object[] { "data", "data", "data",
                "data", "data", "data" });
 }