Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle table which sorting and adding data parallel?

I am facing problem of duplicate rows in the JXTable. If I sort the JXTable data while the new rows are being inserted in JXTable, the final result in JXTable shows duplicate rows that make invalid result in table. Even it also shows correct count of rows that has been inserted but some rows are completely missing whereas some rows are found duplicate in JXTable.

If I sort the JXTable after all data has been inserted successfully then it is showing correct data i.e no duplicate rows and no rows missing.

code example : I have a method to which I am passing defaultTableModel and here is am adding items in the table

public void addingItems(DefaultTableModel  defaultTableModel)
{
for(int i=0;i< numberofItems;i++){
Vector vobject = new Vector();
vobject.add("...");
vobject.add("xxx");
vobject.add("yyy");
...
..
vobject.add("");
defaultTableModel.addRow(vobject);
}

one the other hand I have adding code of sorting at tableHeader actionlistener

tableheader.addMouseListener(new MouseListener() {
 public void mouseClicked(MouseEvent e) {
     Vector data = defaultTableModel.getDataVector();   
     Collections.sort(data, new ColumnSorter(colIndex, ascending));
}

});

I have put code in the synchronized block but not getting success.

Please provide a better solution to handle this issue.

like image 364
Tej Kiran Avatar asked Nov 13 '22 04:11

Tej Kiran


1 Answers

I have put code in the synchronized block but not getting success.

Because you have to handle synchronization not only in your sort handler block, but also on each modification operation.

For example:

  ... 
  vobject.add("");
  synchronized(monitor) {
    defaultTableModel.addRow(vobject);
  }
}

and

  ...
  Vector data = defaultTableModel.getDataVector();
  synchronized(monitor) {
    Collections.sort(data, new ColumnSorter(colIndex, ascending));
  }
}

In this case your UI could look somewhat unresponsive if you have a lot of data in your table because sort is N^2*logN. If you have somewhat about 200 entries - it wouldn't make a problem for you.

like image 184
Artem Oboturov Avatar answered Nov 16 '22 03:11

Artem Oboturov