remove rows from JTable with AbstractTableModel

TheSpaceboy0 picture TheSpaceboy0 · Dec 14, 2012 · Viewed 9.3k times · Source

I would like to remove selected row from JTable with AbstractTableModel using a button.

The code below works with DefaultTableModel:

...
MyTableModel mtb;
...
private String[]....
private Object[][]...
...
JTable table = new JTable(mtb)
JButton delete;
...
 public void actionPerformed(ActionEvent e) {

        if(e.getSource().equals(delete))
         {
                 if(table.getSelectedRow()<0)
                 {
                  JOptionPane.showMessageDialog(this,"Select row");

                 }
                 else
                 {
                     mtb.removeRow(table.getSelectedRow()); 

                 }
         }
     }

but it deosn't work with AbstractTablemodel.

I have a little mess in my code so here is java example from oracle page that can be used:

Thanks!

Answer

trashgod picture trashgod · Dec 14, 2012

For AbstractTableModel, you have to implement your own removeRow() based on your model's internal data structure(s), but you can study the source of DefaultTableModel as a guide on which event(s) to fire. For example,

public void removeRow(int row) {
    // remove a row from your internal data structure
    fireTableRowsDeleted(row, row);
}