我尝试通过创建包含相同信息的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();
}
}
}
我的问题是,是否有一种更简单的方法可以做到这一点,不需要创建两个相同的数据阵列。谢谢。
答案 0 :(得分:1)
是一种更简单的方法,
这可能是最简单的方法。您可以使用此数据创建一个新的TableModel并重置该表的模型。
但问题是您需要两份数据副本。
不需要创建两个相同的数据阵列。
然后,您需要跟踪单元格中的数据何时更改。
因此,您可以保留HashMap
,其中键是行/列,数据是原始值。因此,在“取消”上,您只需遍历HashMap
并恢复地图中找到的每个键的数据。
您可以使用Table Cell Listener侦听对TableModel的更改。然后,每当生成事件时,您将检查HashMap的行/列以查看它是否具有值。如果没有,您将保存原始值。