Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

java - Deleting all the rows in a 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...