我需要删除 JTable 中的所有行。
我已经尝试了以下两种方法:
/**
* Removes all the rows in the table
*/
public void clearTable()
{
DefaultTableModel dm = (DefaultTableModel) getModel();
dm.getDataVector().removeAllElements();
revalidate();
}
和
((DefaultTableModel)table.getModel()).setNumRows(0);
两者都不会删除所有行。有什么想法吗?
最佳答案
我们可以为此使用 DefaultTableModel.setRowCount(int),引用 Java 的文档:
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.
这意味着,我们可以像这样清空一个表:
DefaultTableModel dtm = (DefaultTableModel) jtMyTable.getModel();
dtm.setRowCount(0);
现在,关于“java 如何丢弃这些行?”,我相信它最终只是调用了一些类似 C 的 free(void*),或者它只是删除了对该内存区域的所有引用并将其留给 GC关心一下,文档并不清楚这个函数是如何在内部工作的。
关于java - 删除 JTable 中的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6232355/