remove rows from JTable with AbstractTableModel

爱⌒轻易说出口 提交于 2019-12-17 20:54:27

问题


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!


回答1:


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);
}



回答2:


DefaultTableModel will itself call fireXX methods whenever there is a change in the table model. But if we use AbstractTableModel then we have to explicitly call fireXX methods. So when ever there is a change in the table just call relevant fireXX method.

For,

inserting a new row to the table use fireTableRowsInserted

deletion (in your case) use fireTableRowsDeleted

update use fireTableRowsUpdated

NOTE: DefaultTableModel has most of all the methods implemented. So unless there is a real need go for AbstractTableModel else stick with DefaultTableModel.



来源:https://stackoverflow.com/questions/13880545/remove-rows-from-jtable-with-abstracttablemodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!