How to delete a line from JTable in Java

Deleting a row in JTable in Java depends on the template of your JTable. JTable uses by default  DefaultTableModel. However, you can also specify your own Table Model.

Delete in DefaultTableModel

DefaultTableModel stores the data in a Vector array, which makes it easier to delete by eliminating only the flat elements in that row with the romoveRow(int line).

import javax.swing.JFrame; 
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;

public class JTableExample extends JFrame{

Object[][] data = {{9,8,7,6},{7,6,5},{6,5,4}};
String[] title = {"c1", "c2", "c3"};

public JTableExample(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);

DefaultTableModel dtm = new DefaultTableModel(data, title);
table.setModel(dtm);
this.getContentPane().add(new JScrollPane(table),BorderLayout.CENTER);
//delete row 2
((DefaultTableModel)table.getModel()).removeRow(1);
pack();
}

public static void main(String[] args) {
new JTableExample();
}
}
Output
jtable defaulttablemodel
Front
delete a row in jtable defaulttablemodel
After

Delete in  AbstractTableModel

If you have created your own model that inherits from  AbstractTableModel, then you must also implement the removeRow. This implementation depends on the nature of your structure that you have implemented to store the data.

For example, if you use a ArrayList JTable model, then it will look like this:

class Model extends AbstractTableModel{

List< object> data = new ArrayList< object> ();
public void removeRow(int line){
this.data.remove(line);
}
}
JTable HashMap Model:

class Model extends AbstractTableModel{

HashMap< Integer, Object[]> data = new HashMap< Integer, Object[]> ();
public void removeRow(int line){
this.data.remove(line);
}
}
And if you're using a two-dimensional array whose elements aren't stored dynamically, then you'll have problems, because there's no function that removes a row from an array. So, you're going to create an offset that will have an unnecessary complexity of (n-k)*m(k; line index) caused by the time and number of operations required to offset all elements.

References:
Oracle documentation: The removeRow method of the DefaultableModel
Developpez.com: Display an array with AbstractTableModel
okipa.be: Display data in a JTable