gpt4 book ai didi

java - 是否有更有效的方法将 JTable 中已编辑的单元格内容重置回之前的内容

转载 作者:行者123 更新时间:2023-12-01 09:25:07 24 4
gpt4 key购买 nike

我尝试通过创建两个包含相同信息的独立数据数组来解决这个问题。其中一个数据数组 (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();
}
}
}

我的问题是是否有一种更简单的方法来做到这一点,不需要创建两个相同的数据数组。谢谢。

最佳答案

is an easier way to do this,

这可能是最简单的方法。您只需使用此数据创建一个新的 TableModel 并重置表的模型即可。

但是问题是您需要数据的两个副本。

one which doesn't require creating two identical data arrays.

然后您需要跟踪单元格中的数据何时更改。

因此,您可以保留一个 HashMap,其中键是行/列,数据是原始值。因此,在“取消”时,您只需迭代 HashMap 并恢复映射中找到的每个键的数据。

您可以使用Table Cell Listener监听 TableModel 的更改。然后,每当生成事件时,您都会检查 HashMap 的行/列以查看它是否有值。如果没有,您将保存原始值。

关于java - 是否有更有效的方法将 JTable 中已编辑的单元格内容重置回之前的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39900307/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com