如何在允许编辑 JTable 中的给定行之前进行检查
这个问题很基本。 我有一个 JTable,显示数据库中的缓存数据。 如果用户单击单元格进行编辑,我想尝试锁定数据库中的该行。 如果锁定不成功,我想阻止编辑。
但我似乎找不到任何干净的方法来完成此任务。 我错过了什么吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在编辑/设置值之前,通过 TableModel.isCellEditable(row,col) 询问表模型该单元格是否可编辑。 在这里你可以实现你的锁。 在 TableModel.setValue(row,col,val) 之后你应该解锁它。 但。 锁定操作应该花费大量时间并且使您的 UI 不负责任。 这很糟糕。 尝试不同的方法。 懒惰失败怎么办? 您锁定该行,检查数据的有效性,如果数据较新则失败。 如果数据没问题,你就把它们放下。 开锁。
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.
Oracle 有一个很好的方法来处理这个问题,但我不知道它的普遍适用性如何。
在 Oracle 中,您可以在 SELECT 语句上使用 FOR UPDATE 来在读取记录时锁定记录。
例如,如果您要获取一行进行显示:
这将允许读取但阻止更新。 如果另一个事务有锁,您的事务将等待,直到它变得可用(或最终超时)。 如果您希望语句在尝试锁定时抛出异常,请添加NOWAIT。
如果该行已被锁定,您将得到:
希望有帮助。
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:
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.
If the row is already locked you will get:
Hope that helps.
因为您必须测试点击,所以您不能使用模型的方式来执行此操作,因此您应该尝试覆盖 JTable 的 public void changeSelection(int rowIndex, int columnIndex, boolean Switch, olean Extend) 方法。 如果该行被锁定,则不要调用 super.changeSelection 并且它应该使该行保持未选中状态。
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.
相反,您可以等到用户实际更改某些内容,然后重写 JTable.editingStopped 在那里完成工作(您甚至可以检查值是否更改),
这样在用户实际更改某些内容之前不会执行锁定。
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.