How do I delete a row from a JTable?
The answer depends on the model you're using...
If you've called setModel() for the JTable in question, you must examine the class of the actual model you're using to see how (and if) it allows row deletion. Note that some models will not allow deletion, others may allow you to delete an entire row, and others may only allow you to delete a single cell at a time.
JTable someTable = new JTable();
the JTable creates an instance of javax.swing.table.DefaultTableModel to store the data. You can grab a reference to this DefaultTableModel and ask it to delete a row. For example:
DefaultTableModel model = (DefaultTableModel)someTable.getModel(); model.removeRow(42);
A couple of things to note:
- removeRow() throws an ArrayIndexOutOfBoundsException if the row doesn't exist in the table
- removeRow() doesn't exist in the TableModel interface, which is why you must cast the result of getModel() to DefaultTableModel. This means that not all TableModels will have this method, but if you're using the default table support it'll be there.