tags:

views:

405

answers:

4

The problem is quite basic. I have a JTable showing cached data from a database. If a user clicks in a cell for editing, I want to attempt a lock on that row in the database. If the lock does not succeed, I want to prevent editing.

But I can't seem to find any clean way to accomplish this. Am I missing something?

A: 

Because you have to test on the click you can't use the model's way of doing this so you should try overriding the JTable's public void changeSelection(int rowIndex, int columnIndex, boolean toggle, oolean extend) method. If the row is locked then don't call super.changeSelection and it should leave the row unselected.

carson
Actually, I'd still want the rows selectable (since I have a function for exporting selected rows which shouldn't require a lock), but your answer gave me the right idea. :)I'm overriding editCellAt() on the JTable instead, and otherwise does just as you recommended.
Fuzzy76
cell selection and editability is not related. In the mentioned isTableCellEditable method you can return false and the JTable will not start editing. But holding a lock on a row until the editing is as also mentioned not a good diea
Peter
+1  A: 

Oracle has a nice way of handling this but I don't know how universally applicable it is.

In Oracle, you can use FOR UPDATE on a SELECT statement to lock a record as you read it.

For example, if you are fetching a row for display:

select * into v_row from my_table where my_table_id = 1
for update;

This will allow reads but prevent updates. If another transaction has a lock your transaction will wait until it becomes available (or timeout, eventually). If you want the statement to throw an exception if you try to lock you add NOWAIT.

select * into v_row from my_table where my_table_id = 1
for update nowait;

If the row is already locked you will get:

ORA-00054: resource busy and acquire with NOWAIT specified.

Hope that helps.

Nick Pierpoint
+2  A: 

Before editing/setting value the table model is asked via TableModel.isCellEditable(row,col) whether this cell is editable. Here you can implement your lock. and after TableModel.setValue(row,col,val) you should unlock this. BUT. The lock operation should take a lot of time and makes your UI un-responsible. And it si BAD. Try different approach. What about lazy fail? You lock the row, check for validity of data and fail if data are newer. If data are OK, you put them down. UNLOCK.

Rastislav Komara
A: 

Instead, you could wait until the user actually changes something, then override JTable.editingStopped to do the work there (you could even check to see if the value changed)

That way no locking is done until the user actually changes something.

John Gardner