Search code examples
swingreferencevectorjtabletablemodel

Editting duplicate row in tableMode, edits original row also


I've created an add row function, that adds either the selected row, or last row to the end of the tableModel. When I go and edit the new row the original row also gets edited. I thought i created a new distinct row or did i create a reference to the original row?

int currentRow = jTable1.getSelectedRow();      

Vector data = tableModel.getDataVector(); 

    System.out.println("Vector size: " + data.size());        
if(data.size()>0){   
    if(currentRow > -1){
        Vector temp = (Vector) data.elementAt(currentRow);
        tableModel.addRow(temp);            
   }else{            
        Vector temp = new Vector(data);
        Vector helper = (Vector) temp.elementAt(temp.size()-1);

        tableModel.addRow(helper);
   }
 }else{
     outputMsg("Failed to add row.");
 }

Solution

  • You did not create a reference to the original row, but both rows use the same Vector instance for their data with the same data objects contained in the vector. So both your original row as your new row are backed by exactly the same data, hence making a modification in one row will be reflected in the other row.

    A possible solution for this is to make a copy of the data represented by that table row, and create a new row based on the copy of that data. How to create that copy will depend on the data, although a very naive implementation could be to use the clone method (and not the clone of the Vector, but of the data contained in the Vector)