![](/img/trans.png)
[英]Overriding Cell Editor for Individual JTable Cells that have been Dynamically Created
[英]Is there a more efficient way to reset the contents of cells that have been edited in a JTable back to what they previously were
我嘗試通過創建2個包含相同信息的單獨數據數組來解決此問題。 這些數據數組(tableData)中的一個在JTable的構造函數中使用,而另一個(oldTableData)在應用程序首次運行時用於將單元格中的值更改回其原始值。 我需要第二個數據數組,因為每次更改表中單元格中的值時,第一個數據數組都會自動更新,是否可以禁用JTable的此功能?
我需要在編輯表中的單元格時單擊“取消”按鈕時使用此功能,因為“取消”按鈕應撤消編輯單元格時所做的所有更改。 到目前為止,這是我對“取消”按鈕的實現:
if(e.getSource().equals(cancelMenuButton)) {
//prints set of edited cells
System.out.println("edited cells: "+editedCells);
///once cancel button is clicked, disable both submit and cancel, as we are out of edit mode
cancelMenuButton.setEnabled(false);
submitMenuButton.setEnabled(false);
//reset values in table
Iterator<Point> iterator = editedCells.iterator();
while(iterator.hasNext()) {
Point point = iterator.next();
System.out.println("Value at "+point.x+", "+point.y+": "+table.getValueAt(point.y, point.x));
System.out.println("Old value at "+point.x+", "+point.y+": "+oldTableData[point.y][point.x]);
table.setValueAt(oldTableData[point.y][point.x], point.y, point.x);
}
editedCells.clear();
//cancel cell editing
CellEditor cellEditor = table.getCellEditor();
if(cellEditor != null) {
if(cellEditor.getCellEditorValue() != null) {
cellEditor.stopCellEditing();
} else {
cellEditor.cancelCellEditing();
}
}
}
我的問題是是否有一種更簡單的方法可以執行此操作,而該方法不需要創建兩個相同的數據數組。 謝謝。
是更簡單的方法
這可能是最簡單的方法。 您可以只使用此數據創建一個新的TableModel並重置表的模型。
但是,問題在於您需要數據的兩個副本。
一個不需要創建兩個相同的數據數組。
然后,您需要跟蹤何時更改單元格中的數據。
因此,您可以保留一個HashMap
,其中鍵是行/列,數據是原始值。 因此,在“取消”上,您只需要遍歷HashMap
並恢復Map中找到的每個鍵的數據。
您可以使用表格單元監聽器來監聽對TableModel的更改。 然后,無論何時生成事件,您都將檢查HashMap的行/列以查看其是否具有值。 如果沒有,您將保存原始值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.