How to add dynamic row into JTable


To add dynamic row into JTable we need Object of DeafultTableModel.
Create one object of DefaultTabelModel, Set Header of Column using setColumnIdentifiers() methods and set this model to tabel.

 DefaultTabelModel dm = new DefaultTabelModel(0,0);  
 String header[] = new String[]{"Col1","Col2","Col3"};  
 dm.setColumnIdentifiers(header);  
 mytable.setModel(dm);

Now using dm , we able add row, delete row from tabel.
To add add row into table we add all element into one vector and using addRow() method we add row into tabel.

 Vector<Object> data = new Vector<Object>();  
 data.add("My Name");  
 data.add(20);  
 data.add(false);  
   
 dm.addRow(data);  

Keep in mid elements in the vector are the row element of JTable, so no of column in the table is equal to no of element in the vector.


For, removing row use removeRow() method.

 dm.removeRow(index);  

Where index is the no of row you want to remove.

If you are using NetBean, you should use above method to set DefaultTableModel or Use Proerties window to set Model to Table. Get model of table using getModel() method, as below.

 DefaultTableModel dm = (DefaultTableModel) mytable.getModel();  


1 comment:

  1. This did the trick for me. Thanks.

    ReplyDelete