1

ive been trying to update the table after the insertion or deletion of items from a abstract table model but whenever i do that, instead of removing the old records and replace with the new ones, the old rows remains and it creates all the rows again without removing the old ones..so i get duplicate items, this is the code im using : for the data inserted :

TestModel tm = new TestModel() ;

                    tm.fireTableRowsInserted(records.length, records.length);

and for the data deleted :

TestModel tm = new TestModel() ;
                    tm.fireTableRowsDeleted(records.length, records.length);

any clue of how to get around with that? any help is greatly appreciated! Kind regards, Romulo Romero

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Ogre3dUser
  • 79
  • 1
  • 3
  • 10
  • Use the DefaultTableModel. It supports methods to dynamically add/remove rows from the model. – camickr May 30 '13 at 04:12
  • You shouldn't be "firing" events outside of the mode, they should only be fired from within the model. The API describes the requirements for these events, in that the data must have already been removed/or inserted from the model. It scares me that your example starts with `new TestModel();`. Only the model attached to the table should be updated and only it will notify the table of updates. A [SSCCE](http://sscce.org/) may produce better answers – MadProgrammer May 30 '13 at 04:22

1 Answers1

2

Create a table with a boolean column. Since using this boolean column you can delete those rows that are selected for deletion. Just like the following screen shot,

enter image description here

Then in your TableModel make a List<StudentDO> such that it will hold all the table data.

Adding a Row:

To add a row just create a new StudentDO and send it to the table model and the model addRow method will add the object to the table list.

Deleting Rows:

For Deleting rows just call a delete method and this should fire event in TableModel such that model should traverse all the rows and check which ever row is selected and delete it.

Note: Deleting rows should be done from the end not from the beginning of the list.

StudentTableModel.java

class StudentTableModel {

    // Required methods code goes here.  

    public void addRow(StudentDO do1) {
        data.add(do1);
        fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1);
    }

    public void deleteRow() {
           for(int rowIndex = data.size() - 1; rowIndex >= 0; rowIndex--) {
            if(data.get(rowIndex).isSelect()) {
          data.remove(rowIndex);
         }
           }
     fireTableDataChanged();
    }
}

P.S: fireXXXMethods should be called only in the model. Because any data change will be responsible of the model.

Amarnath
  • 8,736
  • 10
  • 54
  • 81