Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting all the rows in a JTable

Tags:

java

swing

jtable

I need to remove all the rows in my JTable.

I have tried both of the following:

/**
 * Removes all the rows in the table
 */
public void clearTable()
{
    DefaultTableModel dm = (DefaultTableModel) getModel();
    dm.getDataVector().removeAllElements();
    revalidate();
}

and

((DefaultTableModel)table.getModel()).setNumRows(0);

Neither of which would remove all the rows. Any ideas?

like image 583
user489041 Avatar asked Jun 03 '11 20:06

user489041


People also ask

How do you clear a JTable?

You must remove the data from the TableModel used for the table. If using the DefaultTableModel , just set the row count to zero. This will delete the rows and fire the TableModelEvent to update the GUI.

How do you make a JTable column not editable?

Right-click on the table cells. From popup menu, choose "Table Contents..". Uncheck the editable check box for the column you want to make it non-editable.

What is JTable TableModel?

The TableModel interface specifies the methods the JTable will use to interrogate a tabular data model. The JTable can be set up to display any data model which implements the TableModel interface with a couple of lines of code: TableModel myData = new MyTableModel(); JTable table = new JTable(myData);


3 Answers

We can use DefaultTableModel.setRowCount(int) for this purpose, refering to Java's Documentation:

public void setRowCount(int rowCount)

Sets the number of rows in the model. If the new size is greater than the current size, new rows are added to the end of the model If the new size is less than the current size, all rows at index rowCount and greater are discarded.

This means, we can clear a table like this:

DefaultTableModel dtm = (DefaultTableModel) jtMyTable.getModel();
dtm.setRowCount(0);

Now, on "how does java discard those rows?", I believe it just calls some C-like free(void*) ultimately somewhen, or maybe it just removes all references to that memory zone and leaves it for GC to care about, the documentation isn't quite clear regarding how this function works internally.

like image 111
Felype Avatar answered Oct 20 '22 09:10

Felype


The following code worked for me:

DefaultTableModel dm = (DefaultTableModel) getModel();
int rowCount = dm.getRowCount();
//Remove rows one by one from the end of the table
for (int i = rowCount - 1; i >= 0; i--) {
    dm.removeRow(i);
}
like image 41
Mihai Avatar answered Oct 20 '22 09:10

Mihai


Something like this should work

DefaultTableModel model = (DefaultTableModel)this.getModel(); 
int rows = model.getRowCount(); 
for(int i = rows - 1; i >=0; i--)
{
   model.removeRow(i); 
}
like image 22
james_bond Avatar answered Oct 20 '22 10:10

james_bond