Removing a Row from a JTable Component

To remove a row of data from a JTable component, you need to remove it from its table model. A simple implementation of a table model that supports the removal of row data is DefaultTableModel.

When removing a row using DefaultTableModel.removeRow(), the index of the row must be specified. Row indices start from 0. For example, if there are 2 rows in a table, the index of the first row is 0 and the index of the second row is 1. Removing a row at index 0 removes the first row.

DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);

// Create some data
model.addColumn("Col1");
model.addRow(new Object[]{"r1"});
model.addRow(new Object[]{"r2"});
model.addRow(new Object[]{"r3"});

// Remove the first row
model.removeRow(0);

// Remove the last row
model.removeRow(model.getRowCount()-1);

Comments

13 Apr 2010 - 1:48am by abhinav (not verified)

good help....

19 Jan 2011 - 4:27am by Anonymous (not verified)

while(mdl.getRowCount()>0)
{
mdl.removeRow(0);
}

23 May 2011 - 2:30pm by Anonymous (not verified)

To clear the whole table:

public void clearTable() {
model.getDataVector().clear(); //Remove all TableData
model.getColumnIdentifiers().clear(); //Remove all Identifiers(Header)
}

23 Aug 2011 - 11:55pm by Hossein (not verified)

23 May 2011 - 2:30pm by Anonymous (not verified)
To clear the whole table:

public void clearTable() {
model.getDataVector().clear(); //Remove all TableData
model.getColumnIdentifiers().clear(); //Remove all Identifiers(Header)
}

thanks for your optimize solution!

25 Sep 2011 - 1:15am by Kris (not verified)

Thank you all. It helped a lot

12 Apr 2012 - 9:18pm by Anonymous (not verified)

pls help me.....I have to delete a selected row in JTable using the Key Event.When i select a row and pressing the Delete Key,the selected row values should be deleted.

How to do this? ....

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.